Question

I'am looking for a way to add intiatlize an associated DB after the parent is created.

I have a simple User model with just the filed username and a related (has_many) child Place model with the field placenames.

After the user was created succsefully, the table of Places should be filled with entry's like: europe, asia, afrika. I think the way to go is to use the after_create method but i can't find how to trigger the creation from my parent model.

Was it helpful?

Solution

You can declare the after_create like this

class User 

  after_create :initialize_places

  def initialize_places
    self.places.create(:placename => 'Europe')
    self.places.create(:placename => 'Asia')
    self.places.create(:placename => 'Africa')
  end
end

And create the user like this

user = User.create(:username => 'The Black Adder')

OTHER TIPS

Hm, not sure what exactly it is you're trying to do.

Are you getting the places to associate the user with from the #create form (e.g. the user can tick off predefined places with checkboxes)? Or can the user supply places via a comma-separated list and the user creation action should weed out duplicates and add new ones to the db on the fly?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top