问题
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