mrb*_*rdo 23 ruby-on-rails ruby-on-rails-3
在Rails中是否可以在不立即将此更改提交到数据库的情况下向现有记录添加关联?例如,如果我有Post has_many:标签
post.tags << Tag.first
Run Code Online (Sandbox Code Playgroud)
这将立即提交到数据库.我尝试过其他方式而不是<<,但没有成功(我想要的是在保存父对象时创建关联).是否有可能获得类似于使用build添加新记录的关联时的行为?
post.tags.build name: "whatever"
Run Code Online (Sandbox Code Playgroud)
我认为这在Rails中有点不一致,在某些情况下,选择执行此操作会很有用.
换句话说,我想要
post.tags << Tag.first # don't hit the DB here!
post.save # hit the DB here!
Run Code Online (Sandbox Code Playgroud)
Isa*_*esh 33
这应该适用于Rails 3.2和Rails 4:
post.association(:tags).add_to_target(Tag.first)
Run Code Online (Sandbox Code Playgroud)
请参阅此要点: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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5523 次 |
最近记录: |