ruby-on-rails-3modelinitializationafter-create

Rails3 - Adding default values to associated table after_create


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.


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')