我在 ActiveRecord rails 中有以下 has_many 关系的代码库:
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。这是我的代码如下:
@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