I have something like this:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
user = User.new
user.profile.something #=> ERROR
What is a proper way to set a default profile object in this case? I have tried this:
class User < ActiveRecord::Base
default_scope :include => :profile
has_one :profile
def after_initialize
self.profile ||= Profile.new(:user => self)
end
end
...but that creates N+1 queries. Any ideas?
Update
This is what I have now, works okay, still looking for something better:
class User < ActiveRecord::Base
default_scope :include => :profile
has_one :profile, :autosave => true
def after_initialize
self.profile = Profile.new(:user => self) if new_record?
end
end
This way, you're going to have a Profile whenever you finally create
your user. Otherwise, the only case is a new_record?
.