It took me two days to figure out how to initialize a new child record from within the parent model, I hope this helps someone:

I’m using devise for authentication and authorization and using devise built-in controllers. My User model has a child Contact model (Contact belongs_to :User) which contains the user’s names and contact information. I preferred not to initialize the content model on new registration in the view (what’s the point of MVC philosophy if you don’t follow it?).

The solution (in Ruby on Rails 2.3.11) is the after_initialize callback


class User < ActiveRecord::Base
  has_one :contact, :dependent => :destroy
  accepts_nested_attributes_for :contact, :allow_destroy => true

  # Devise modules will go here

  attr_accessible :contact_attributes

  def after_initialize
    self.build_contact if self.contact.nil?
  end
end

and voilà! Your Contact model will be initialized and thus shown in the view when you use f.fields_for :contact

As you can probably figure out, I’m a huge of of Hoegaarden! I believe it is THE BEST beer in the world! Served with a slice of lemon it has an unmistakable and unbeatable taste!