gpt4 book ai didi

ruby-on-rails - 添加关联(<<)而不提交到数据库

转载 作者:行者123 更新时间:2023-12-03 11:16:22 25 4
gpt4 key购买 nike

是否可以在 Rails 中向 添加关联?现有 记录而不立即将此更改提交到数据库?
例如。如果我有 Post has_many :tags

post.tags << Tag.first

这将立即提交到数据库。我尝试了其他方法而不是<<,但没有成功(我想要的是在保存父对象时创建关联)。
是否有可能获得像使用 build 将关联添加到新记录时那样的行为?
post.tags.build name: "whatever"

我认为这在 Rails 中有点不一致,在某些情况下,有一个选项会很有用。

换句话说,我想要
post.tags << Tag.first # don't hit the DB here!
post.save # hit the DB here!

最佳答案

这应该适用于 Rails 3.2 和 Rails 4:

post.association(:tags).add_to_target(Tag.first)

请参阅此要点: https://gist.github.com/betesh/dd97a331f67736d8b83a

请注意,保存父级会保存子级,并且在保存之前不会设置 child.parent_id。

编辑 12/6/2015:
对于多态记录:
post.association(:tags).send(:build_through_record, Tag.first)
# Tested in Rails 4.2.5

关于ruby-on-rails - 添加关联(<<)而不提交到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197359/

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