Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create association before record is saved

So, I'm admittedly a Rails newbie, and I'm running into what must be a fairly common issue, but I can't find the answer here.

I have a model Foo like this:

class Foo < ActiveRecord::Base
  has_many :bars
end

Bars belongs_to Foo, all that works. Now I want to create a Foo and build Bar at the same time. Like this:

f = Foo.new(:baz => 'baz')
bars.each do |b|
  f.bars.build(:bizzy => b[:bizzy])
end
f.save

I know this won't work because the parent record doesn't exist, so the association doesn't exist, but there must be a way to do this. I've temporarily gotten around it by editing to this:

f = Foo.new(:baz => 'baz')
f.save
f = Foo.find(:first, :conditions => {:baz => 'baz'})
bars.each do |b|
  f.bars.create(:bizzy => b[:bizzy])
end

But that is not clean, and is all around unpleasant.

What is the right way to do this?

like image 451
Eugene Avatar asked Apr 10 '12 13:04

Eugene


1 Answers

In the first line you can just use create instead of new. You don't need f.bars.create or f.bars.build, because the bar object already exists. I would do this:

f = Foo.create(:baz => 'baz')

bars.each do |b|
  f.bars << b
end

Personally I wouldn't iterate over the bars, but just use update_all:

f = Foo.create(:baz => 'baz')
bars.update_all(:foo_id => f.id)

Edit: it's possible to do this without saving the record first. This works for me:

f = Foo.new(:baz => 'baz')

bars.each do |b|
  f.bars << b
end

f.save
like image 169
Mischa Avatar answered Oct 31 '22 22:10

Mischa