«Попытка вызвать частный метод» с помощью учебника депо - PullRequest
0 голосов
/ 28 июня 2010

«Попытка вызова частного метода» с руководством по депо

В моей модели "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). Это ответ или есть другая возможная причина этого?

1 Ответ

4 голосов
/ 28 июня 2010

укажите весь код 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...