Automatically create one child record when parent record is initially created

Sorry for the newbie question in advance... I've got three models, a user, site and user_site model. A site can have many users and a user can have many sites. The relationship between these two is stored in user_site. In my model defs user and sites both have has_many user_sites statement. Within my user_sites file, there are two belongs_to statements, one for user and one for site. within the What I'm looking to do is when a user is created initially to automatically create a record in user_site for a default site (I have it contained in an instance variable within the user controller). What I'm not sure is how to most effectively do this so that the generated id for user is automatically pulled into the child record in user_site, basically I'm trying to come up with an efficient method for creating the user and user_site records. Any guidance is much appreciated.

Hi Chris,

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 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 =   user_site_rec.user_id =   unless      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


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]) if    @user.user_sites << UserSite.create(: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.

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]) @user.user_sites << => if ...

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.