是否有一个领域特定语言用于在AR关系中创建一个与:dependent => destroy相反的对象(换句话说,创建一个对象以使其始终存在)。例如,我有以下内容:
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)来做这件事?
发布于 2012-09-14 01:19:38
不,因为实际上没有这方面的用例。如果您的记录没有关联的记录就不能存在,那么您可能应该阻止记录被保存,而不是使用某种伪空对象来代替它。
最接近的近似方法是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发布于 2012-09-14 01:36:18
您应该只在create上运行此代码一次,并在此处使用方便的方法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
endhttps://stackoverflow.com/questions/12411512
复制相似问题