Ruby on Rails:在创建父级时创建具有默认值的子级

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

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

我认为它将与父模型上的after_create类似,但我不确定如何设置它。

修订:我修改了使用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 

添加…

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

请参阅has_many和has_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 

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

你没有指定(或我覆盖它)你正在使用什么样的关系。 如果您使用的是一对一关系,例如“has_one”,则无法创建。 在这种情况下,你必须使用这样的东西:

在parent.rb中

 has_one :child before_create {|parent| parent.build_child(self)} 

after_create可能也可以,但没有测试过。

而在child.rb

 belongs_to :parent 

在我当前的应用程序中设置用户模型时,我正在努力解决这个问题。

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html您可以看到has_one不支持parent.build或parent.create

希望这可以帮助。 我自己也是Ruby新手,慢慢开始穿越Ruby丛林。 一个不错的旅程,但很容易迷失。:)