首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用depot教程“尝试调用私有方法”

使用depot教程“尝试调用私有方法”
EN

Stack Overflow用户
提问于 2010-06-28 13:39:33
回答 1查看 953关注 0票数 0

使用depot教程“尝试调用私有方法”

在我的"cart.rb“模型中,我有

代码语言:javascript
复制
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“中我有

代码语言:javascript
复制
  def create 
    @cart = find_or_create_cart 
    product = Product.find(params[:product_id]) 
    @line_item = @cart.add_product(product.id)
  .....

当我选择一个项目将其添加到购物车时,我得到一个“尝试调用私有方法”错误。

应用程序跟踪是

代码语言:javascript
复制
/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)。这就是答案,还是有其他可能的原因?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-06-28 13:46:32

如果possible.maybe你的add_product方法在某个私有方法下,那么给出cart.rb的所有代码,比如。我知道这应该是评论,我想用例子来解释它,所以我把它粘贴在答案中。

代码语言:javascript
复制
 private
   def self.some_method
     #some code 
   end

   def add_product(product_id) 

注释中的代码如下所示

代码语言:javascript
复制
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更改为

代码语言:javascript
复制
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
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3130294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档