gpt4 book ai didi

ruby-on-rails - 为什么 ActiveRecord 有时只是自动提供相互关联?

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:25 24 4
gpt4 key购买 nike

在使用 activerecord 时,我注意到在构建关联时,只有在互惠模型已经保存的情况下,才会自动提供互惠关联。如果尚未保存,则必须手动定义此相互关联。我想知道这是故意的还是错误,因为它工作或失败的唯一区别是互惠模型是否已保存。

我希望通过以下要点中描述的三个场景来阐明这一点。

http://gist.github.com/527046

我希望场景 1 在没有场景 3 中显示的额外分配步骤的情况下工作。事实并非如此。

最佳答案

原因很简单——当你通过父对象尚未保存的关联创建对象时,其关联的外键不能有值,因为关联的记录尚未保存。举例说明:

# Registration announcement is not saved at this point, so it has no ID.
@a1 = @e1.build_registration_announcement(:announcement => "Please bring a favorite baked dish.")
# Registration is built without a registration_announcement_id, as @a1 has no ID to pass on.
@a1.registrations.build(:contact_email => "jdoe@yahoo.com", :adults => 1)
#registration doesn't know about its unsaved registration_announcement parent

# Registration announcement is created and saved. ID exists.
@a2 = @e2.create_registration_announcement(:announcement => "Fall house cleaning!")
# Since the Registration announcement has an ID, registration_announcement_id is set on the built associated registration
@a2.registrations.build(:contact_email => "tara.smith@yahoo.com", :adults => 5)
#registration knows about its saved registration_announcement parent

这有点出乎意料,因为您可能逻辑上希望 Rails 保持对象关联,然后在保存时分配关联外键,但它似乎不是那样工作的。

关于ruby-on-rails - 为什么 ActiveRecord 有时只是自动提供相互关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3494172/

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