使用depot教程“尝试调用私有方法”
在我的"cart.rb“模型中,我有
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在"line_items_controller.rb“中我有
def create
@cart = find_or_create_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product(product.id)
.....当我选择一个项目将其添加到购物车时,我得到一个“尝试调用私有方法”错误。
应用程序跟踪是
/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'我看到一些关于类似错误的讨论,听起来答案似乎是升级到ruby 1.9 (我使用的是1.8.7)。这就是答案,还是有其他可能的原因?
发布于 2010-06-28 13:46:32
如果possible.maybe你的add_product方法在某个私有方法下,那么给出cart.rb的所有代码,比如。我知道这应该是评论,我想用例子来解释它,所以我把它粘贴在答案中。
private
def self.some_method
#some code
end
def add_product(product_id) 注释中的代码如下所示
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 您可以在关闭类之后添加方法。把类的结尾放在方法的结尾之后,我打赌它会起作用的。
将cart.rb更改为
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 methodhttps://stackoverflow.com/questions/3130294
复制相似问题