如何使用 ActiveRecord 将一对多对象添加到父对象 [英] How to add one-to-many objects to the parent object using ActiveRecord

查看:36
本文介绍了如何使用 ActiveRecord 将一对多对象添加到父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 ActiveRecord rails 中的 has_many 关系,我有以下代码库:

I have the following code base for has_many relation in ActiveRecord rails:

class Foo < ActiveRecord::Base
  has_many :foo_bars
end

class Bar < ActiveRecord::Base
end  

class FooBar < ActiveRecord::Base
  belongs_to :foo
  belongs_to :bar
end 

如何在创建过程中将 FooBar 条目添加到 Foo.这是我的代码如下:

How do i add FooBar entries to Foo during creation. This is my code as follows:

@foo = Foo.create(params[:foo])
bars = params[:bars] # bars in a array of string format
bar_ids = bars.collect{|b| b.to_i}

@foo.foo_bars << bar_ids
@foo.save

推荐答案

尝试

@foo = Foo.create(params[:foo])
@foo.foo_bars << params[:bars].map {|s| FooBar.new(:bar_id => s.to_i)}  
@foo.save

它为 params[:bars] 集合中的每个 id 构建一个新的 FooBar 实例.最后的 save 将创建 @fooFooBar.有关关联的帮助,请参阅文档此处.

It build a new FooBar instance of each id in the params[:bars] collection. The final save will create both the @foo and the FooBar. See doc here for help on associations.

对于版本:

@foo = Foo.find(params[:id])
@foo.foo_bars = params[:bars].map {|s| @foo.foo_bars.where(:bar_id => s.to_i).first_or_initialize }  

这篇关于如何使用 ActiveRecord 将一对多对象添加到父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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