开发者

"Attempt to call private method" with depot tutorial

"Attempt to call private method" with depot tutorial

In my "cart.rb" model I have

def add_product(product_id) 
  current_item = line_items.where(:product_id => product_id).first 
  if current_item
    current_item.quantity += 1
  else
    current_item = LineItem.new(:product_id=>product_id)
    line_items << current_item
  end
  current_item
end

And in "line_items_controller.rb" I have

  def create 
    @cart = find_or_create_cart 
    product = Product.find(params[:product_id]) 
    @line_item = @cart.add_product(product.id)
  .....

When I select an item to add it to the cart I get a "Attempt to call private method" error.

Application trace is

/Users/machinename/.gem/ruby/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:236:in `method_missing'
/Users/machinename/Documents/rails_projects/depot/app/controllers/line_items_controller.rb:46:in `create'

I saw some discussion of an error similar and it sounded like the answer was upgrade to ruby 1.9 (I am using 1.8.7). Is that th开发者_StackOverflow中文版e answer or is there another possible cause of this?


give all the code of cart.rb if possible.maybe your add_product method is under some private method like. I know this should be comment i want to explain it with example so i paste it in answer.

 private
   def self.some_method
     #some code 
   end

   def add_product(product_id) 

your code from the comment is look like following

class Cart < ActiveRecord::Base 
  has_many :line_items, :dependent => :destroy 
end #this end is creating problem

  def add_product(product_id)
    current_item = line_items.where(:product_id => product_id).first 
    if current_item 
      current_item.quantity += 1 
    else 
      current_item = LineItem.new(:product_id=>product_id)
      line_items << current_item 
    end 
    current_item 
  end 

you add your method after closing the class. put end of class after the end of method and i bet it will work.

change cart.rb to

class Cart < ActiveRecord::Base 
  has_many :line_items, :dependent => :destroy 


  def add_product(product_id)
    current_item = line_items.where(:product_id => product_id).first 
    if current_item 
      current_item.quantity += 1 
    else 
      current_item = LineItem.new(:product_id=>product_id)
      line_items << current_item 
    end 
    current_item 
  end 

end #this end should after the end of class method
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜