Ruby on Rails:在创建父级时使用默认值构建子级

Ret*_*eti 10 ruby-on-rails parent-child

我有父母和孩子的模特关系.在子的migration.rb中,子模型的列各自具有默认值(parent_id列除外).

当我创建一个新的父对象时,我该如何创建它以便创建一个子对象并将其保存到其表中,其中包含来自默认值的数据以及parent_id?

我认为它将与after_create父模型上的某些东西有关,但我不确定如何设置它.

Lar*_*y K 14

修订:我修改了使用before_create和构建而不是创建相关模型的答案.一旦父节点被保存,ActiveRecord机器就会负责保存相关的模型.

我甚至测试了这段代码!

# in your Room model...
has_many :doors

before_create :build_main_door

private

def build_main_door
  # Build main door instance. Will use default params. One param (:main) is
  # set explicitly. The foreign key to the owning Room model is set
  doors.build(:main => true)
  true # Always return true in callbacks as the normal 'continue' state
end

####### has_one case:

# in your Room model...
has_one :door
before_create :build_main_door
private
def build_main_door
  # Build main door instance. Will use default params. One param (:main) is
  # set explicitly. The foreign key to the owning Room model is set
  build_door(:main => true)
  true # Always return true in callbacks as the normal 'continue' state
end
Run Code Online (Sandbox Code Playgroud)

添加...

构建方法由拥有模型的机器通过has_many语句添加.由于该示例使用has_many:doors(型号名称Door),因此构建调用是doors.build

请参阅has_manyhas_one文档以查看添加的所有其他方法.

# If the owning model has
has_many :user_infos   # note: use plural form

# then use
user_infos.build(...) # note: use plural form

# If the owning model has
has_one :user_info     # note: use singular form

# then use
build_user_info(...) # note: different form of build is added by has_one since
                     # has_one refers to a single object, not to an 
                     # array-like object (eg user_infos) that can be 
                     # augmented with a build method
Run Code Online (Sandbox Code Playgroud)

Rails 2.x为关联引入了自动保存选项.我不认为它适用于上述(我使用默认值).自动保存测试结果.