代码之家  ›  专栏  ›  技术社区  ›  Maestro1024

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

  •  0
  • Maestro1024  · 技术社区  · 14 年前

    使用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'
    

    我看到一些关于类似错误的讨论,听起来好像答案是升级到Ruby1.9(我使用的是1.8.7)。这是答案还是有其他可能的原因?

    1 回复  |  直到 14 年前
        1
  •  4
  •   Salil    14 年前

    如果可能的话,给出cart.rb的所有代码。也许您的add_product方法是在类似这样的私有方法下进行的。我知道这应该是评论,我想用例子来解释它,所以我把它粘贴在答案中。

     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