ruby on rails - add to has_many association and use activerecord callback -


i have 2 models, foo , bar. foo has_many bars. i'm trying following in foo model

add_bar?(blah)   bar = bar.new   bar.foo = self   bars << bar   save end  before_save   #stuff involving bars potentially cause rollback end 

that doesn't work because adding bar bars saves it, , i'd bar created if foo saved.

i saw someone suggest using transaction , rescuing activerecord::recordinvalid exceptions. however, save! throws other types of exceptions, , don't think want catch every exception because mask problems want show.

i tried saying in bar's model

before_create { foo.save } 

but didn't work wanted. when save returned false, added object.and seems weird way of doing anyway.

what's normal way of doing this?

you can use

foo.bars.build 

to initialise bar belonging foo


Comments