2013-05-25 57 views
0

在嵌套模型和表單域的背景條件下,在創建一個孩子的值(大小)的家長和投入,目標是對孩子的值應用的條件以確定後續值(產品)時,所有內創建父動作更新屬性後創建以下適用於其他屬性

class QuoteItem < ActiveRecord::Base 
    belongs_to :quote, :inverse_of => :quote_items 
    belongs_to :product 

class Quote < ActiveRecord::Base 
    has_many :quote_items, :inverse_of => :quote 

這不能作爲一個預先模型的方法來執行的,因爲該模型沒有則params的想法。 試圖定義一個after_create回調QuoteItem

after_create :set_product 
    def set_product 
    @quote_item.product_id = Product.where(['min <= ? AND max >= ?', @quote_item.size, @quote_item.size]).first.select[:id]  
    end 

不註冊產品ID。

更簡潔的方式可能是通過所述控制器以重新加載數據。在操作創建

respond_to do |format| 
     if @quote_item.save 
     set_product 
     @quote_item.update_attribute([:quote_item][:product_id]) 
     format.html { redirect_to @quote_item, notice: 'Quote item was successfully created.' } 

具有相同的NIL結果

+0

行動'做after_create'不會保留 – Ven

+0

確定。然而,在保存之前和發出create命令之後仍然會被忽略:----- def create bim = Product.where(['min <=?AND max> =?',params [:quote_item] [:size ],則params [:quote_item] [:大小]])第一 PARAMS [:quote_item] [:尺寸] = BIM @quote_item = QuoteItem.new(PARAMS [:quote_item]) – Jerome

回答

1

該解決方案實際上是在after_create是可能的。 在嵌套模式,更新後的屬性創建

after_create :set_product 

private 

    def set_product 
    product_id = Product.where(['min <= ? AND max >= ?', self.size, self.size]).first.id 
    update_attributes(:product_id => product_id) 
    end 
相關問題