2013-05-25 59 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 
相关问题