2012-09-13 13 views
1

创建一个对象的实例是否有在AR关系,那将是:dependent => destroy相反创建的对象的DSL(即创建一个对象,以便它始终存在)。说,例如,我有以下几点:如何在默认情况下在HAS_ONE关系

class Item < ActiveRecord::Base 
    #price 
    has_one :price, :as => :pricable, :dependent => :destroy 
    accepts_nested_attributes_for :price 
    .... 

class Price < ActiveRecord::Base 
    belongs_to :pricable, :polymorphic => true 
    attr_accessible :price, :price_comment 

我想我想的要创建的代价,即使我们没有指定价格每一次?是唯一的(或最好的)选项来做这个回调,还是有办法通过DSL来做到这一点(类似于:denpendent => :destroy)?

+0

没有价格/ price_comment创建的对象? – meagar

+0

见下文,是否没有价格是免费的? – timpone

+0

那有什么区别?如果您使用'null'或'0.00'价格创建'Price'对象,而不是创建价格对象?如果您*需要*价格,则应强制用户输入价格或明确选择“免费”。 – meagar

回答

0

没有,因为几乎没有用例此。如果记录不能没有相关的记录存在,则可能应该防止记录被保存,不里上演某种伪空对象来代替它。

的最接近将是一个before_save回调:

class Item < ActiveRecord::Base 
    has_one :price, :as => :pricable, :dependent => :destroy 
    accepts_nested_attributes_for :price 

    before_save :create_default_price 

    def create_default_price 
    self.price ||= create_price 
    end 

end 
0

您应该只运行这段代码上创建一个时间和使用的便捷方法create_price这里:为什么你会想要一个价格

class Item < ActiveRecord::Base 
    has_one :price, :as => :pricable, :dependent => :destroy 

    accepts_nested_attributes_for :price 

    after_validation :create_default_price, :on => :create 

    def create_default_price 
    self.create_price 
    end 
end 
+0

pricable确实看起来很时髦(虽然价格不太好看 - 但肯定是正确的)。谢谢。 – timpone