Topic: undefined method

Hi


Why im getting this one undefined method 'with_item' for nil:NilClass??

i have a namespace model

module MyV
   class ItemDisplay < Connector::MyConnector
 set_primary_keys :user_id, :item_id
  belongs_to: user, foreign_key =>user_id
         
            named_scope :with_item, :conditions =>["item_counter > 0]
   end
end

and in my controller

  // will not list all the code but will just put where the error start 
module MyV
    class ItemsController < ApplicationController
    
   
    def listitems
    @results.concat current_user. item_display.with_item
  end

  end

end

and here is the connection part between the user and item display  users the model part

 has_one : item_display , :class_name => 'MyV::ItemDisplay, :foreign_key:user_id

Re: undefined method

First of all, to define a simple scope, we use the scope method inside the class, passing the ARel query that we’d like run when this scope is called:

class Post < ActiveRecord::Base
  scope :published, where(:published => true)
end

And you should call the scope method as as class method:

Post.published

In your case you put it as follows (by the way, there is a space between current_user and item_display :

def listitems
    @results.concat current_user. item_display.with_item
end

Second, the error message tells it itself:

undefined method 'with_item' for nil:NilClass

what means that:
1. item_display variable is null
2. there is no instance method 'with_item' in the class of object item_display.

See more on scopes at Rails Guides.

Re: undefined method

HI,
thanks for the info between there is no space between current_user and item_display current_user.item_display.with_item


for the number 2 that you told me.. how can I instance the method 'with_item' ?  since the new_item is already defined as named_scope?
this error only occur if I use the namespace,

im new to the rails environment

Re: undefined method

You should redefine the scope method as follows, suppose that item_counter is an attribute in your table:

module MyV
   class ItemDisplay < Connector::MyConnector
     set_primary_keys :user_id, :item_id
      belongs_to: user, foreign_key =>user_id         

      scope :with_item, where(:item_counter > 0)
   end
end

Later you can the above scoped method as any class method:

results_with_items = ItemDisplays.with_item

By the way, you model does not inherits from ActiveRecords::Base but from some unknown Connector::MyConnector class. It should inherits the AR Base, if not - you will not be able to call AR methods.

Even if you are a newby, everyone starts using Ror one day, start from rails guides to have an idea on how the things work in Rails: http://guides.rubyonrails.org/

Last edited by Javix (2013-02-08 07:01:25)