I think I've improved on it and made it transactional (please correct me if I'm wrong). My new code look as follows:
@user = User.new(params[:user]) @user.user_sites << UserSite.new(:site_id => @current_site.id) if @user.save ... I'm using the new method instead of the create on the UserSite object. From what I could tell in the docs, when done this way, the creation of the user (parent record) and the usersite (child record) are automatically included in a transaction as an atomic unit, so I shouldn't have to do anything more. As I said above please correct me if I'm misunderstanding something here. On Aug 29, 8:53 pm, Chris <[email protected]> wrote: > I am using Rails 3. I got it to work with the following code, but it > is not currently transactional (if the creation of a UserSite fails > the original user record will still exist in the db). > > @user = User.new(params[:user]) > if @user.save > �[email protected]_sites << UserSite.create(:site_id => @current_site.id) > ... > end > > While this works I'm not sure if there is a better way to accomplish > this (some Rails goodness I'm not familiar with). If anyone has an > opinion on it, please let me know. > > 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.

