How to add one-to-many objects to the parent object using ActiveRecord

懵懂的女人 提交于 2019-12-08 04:37:58

问题


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 

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

回答1:


Try with

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

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.

For edition:

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


来源:https://stackoverflow.com/questions/14210364/how-to-add-one-to-many-objects-to-the-parent-object-using-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!