bdwain
bdwain

Reputation: 1745

add to has_many association and use activerecord callback

I have 2 models, Foo and Bar. Foo has_many bars. I'm trying to do something like the following in my Foo model

add_bar?(blah)
  bar = Bar.new
  bar.foo = self
  bars << bar
  save
end

before_save do
  #stuff involving bars that could potentially cause a rollback
end

That doesn't work because adding the bar to bars saves it, and I'd like the bar to only be created if the Foo is saved.

I saw someone suggest using a transaction and rescuing ActiveRecord::RecordInvalid exceptions. However, save! throws other types of exceptions, and I don't think I want to catch every exception because that would mask problems that I do want to show.

I also tried saying in Bar's model

before_create { foo.save }

but that didn't work like I wanted. Even when save returned false, it added the object.And it seems like a weird way of doing it anyway.

What's the normal way of doing something like this?

Upvotes: 0

Views: 95

Answers (1)

sites
sites

Reputation: 21815

You can use

foo.bars.build

To initialise a bar belonging to foo

Upvotes: 1

Related Questions