gpt4 book ai didi

ruby-on-rails - Ruby on Rails : Building a child with default values when its parent is created

转载 作者:行者123 更新时间:2023-12-04 03:24:02 25 4
gpt4 key购买 nike

我有父子模型关系。在 child 的 migration.rb 中,child 模型的每个列都有默认值(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

添加...

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

docs for 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

Rails 2.x 引入了关联的自动保存选项。我认为它不适用于上述情况(我使用的是默认值)。 Autosave testing results.

关于ruby-on-rails - Ruby on Rails : Building a child with default values when its parent is created,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com