Ruby on Rails after_save错误

时间:2012-06-20 12:23:10

标签: ruby-on-rails callback save ruby-on-rails-3.2

我正面临以下问题,因为我是一个新手上的ruby on rails而且我也无法完全理解after_save回调,已经卡住了

    class StoreOpeningStock < ActiveRecord::Base
     after_save :add_stock

     def add_stock
        s = Stock.find_by_product_id(self.product_id)
        if s.product_id?
        s.update_attributes(:product_id => self.product_id, :quantity => self.quantity, :price => self.price)
        else    
        Stock.create(:product_id => self.product_id, :quantity => self.quantity, :price => self.price)
  end
    end
    end

我将此视为错误

  

未定义的方法product_id

基本上只是检查股票是否有产品?如果是..更新其他创建新股票..我感觉问题是s.product_id ...但不确定..关于这个主题的任何指导将有助于很多...提前谢谢。

1 个答案:

答案 0 :(得分:3)

我认为问题在于这段代码:

if s.product_id?

原则上 product_id?方法不存在,而且你想要的是这样的:

if s

这将检查您之前的查询中数据库中是否存在 s 。如果 s 为nil,则创建新记录。