首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在默认情况下创建has_one关系中对象的实例

如何在默认情况下创建has_one关系中对象的实例
EN

Stack Overflow用户
提问于 2012-09-14 01:17:11
回答 2查看 81关注 0票数 1

是否有一个领域特定语言用于在AR关系中创建一个与:dependent => destroy相反的对象(换句话说,创建一个对象以使其始终存在)。例如,我有以下内容:

代码语言:javascript
运行
复制
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)来做这件事?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-09-14 01:19:38

不,因为实际上没有这方面的用例。如果您的记录没有关联的记录就不能存在,那么您可能应该阻止记录被保存,而不是使用某种伪空对象来代替它。

最接近的近似方法是before_save回调:

代码语言:javascript
运行
复制
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
EN

Stack Overflow用户

发布于 2012-09-14 01:36:18

您应该只在create上运行此代码一次,并在此处使用方便的方法create_price

代码语言:javascript
运行
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12411512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档