I am using Rails 3. I got it to work with the following code, but I haven't done anything to make it transactional (a user record will get created even if the second creation fails)
@user = User.new(params[:user]) if @user.save @user.user_sites << UserSite.create(:site_id => @current_site.id) On Aug 29, 2:33 pm, Bill Walton <[email protected]> wrote: > On Sun, Aug 29, 2010 at 12:34 PM, Chris <[email protected]> wrote: > > How would I handle a failure in that second piece? Can I put it in > > transaction and roll it back? > > Probabl, though you'd have to throw an exception for a transaction to > be effective. IIRC, Rails3 has support for creating associated > records built in but I haven't gotten around to working with 3 and you > didn't say what version you're using. > > The easiest, most readable thing to do might be to just, in the controller... > > if @user.save and @user.user_site > .... > > It's probably better, though, to move it into the User model's > after_create (untested code) > > after_create :create_default_user_site_rec > > def create_default_user_site_rec > user_site_rec = UserSite.new > user_site_rec.user_id = self.id > unless user_site.save > self.destroy > false > end > end > > Tricky thing here is I'm not sure off the top of my head if the > failure of the after_create and its returning false will translate > into the save itself returning false. Sorry I don't have the time to > run it to ground for you. Hopefully this will give you some options > to investigate. > > Best regards, > Bill > > end -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

