添加关联 (<<) 而不提交到数据库 [英] Add association (<<) without committing to database

查看:37
本文介绍了添加关联 (<<) 而不提交到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible in Rails to add an association to an existing record without immediately committing this change to the database? E.g. if I have Post has_many :tags

post.tags << Tag.first

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

This will commit to database immediately. I've tried other ways instead of <<, but without success (what I want is to create the association when saving the parent object). Is it possible to get behavior like when you are adding association to a new record with build?

post.tags.build name: "whatever"

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

I think this is kind of inconsistent in Rails, in some cases it would be useful to have an option to do this.

换句话说,我想要

post.tags << Tag.first # don't hit the DB here!
post.save # hit the DB here!

推荐答案

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

This should work in Rails 3.2 and Rails 4:

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

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

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

Note that saving the parent saves the child and that child.parent_id is NOT set until you save it.

编辑 2015 年 6 月 12 日:对于多态记录:

EDIT 12/6/2015: For a polymorphic record:

post.association(:tags).send(:build_through_record, Tag.first)
# Tested in Rails 4.2.5

这篇关于添加关联 (&lt;&lt;) 而不提交到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆