“尝试使用软件仓库教程调用私有方法”
在我的“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)。这是答案还是另一个可能的原因?
答案 0 :(得分:4)
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 method