1

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.

2 Answers 2

3

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')
Sign up to request clarification or add additional context in comments.

2 Comments

@JochenLeinberger Good. If the solution is OK, you should accept the answer. Thank you.
@Baldrick... sorry just accepeted it! Thanks again!
0

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?

1 Comment

hi, the idea was to populate the child table of each users with a predefined set of values whenever a new user was created. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.