Default Values for Associations in Rails
Sometimes in a Rails app, you'd like to have a default value for an association. Consider the following example from a Stack Overflow question:
class User < ActiveRecord::Base
has_one :profile
end
class Profile < ActiveRecord::Base
belongs_to :user
end
user = User.new
user.profile.something #=> ERROR
Rails doesn't provide a built-in way to specify a default value, but we can do it ourselves:
class User < ActiveRecord::Base
has_one :profile
def profile_with_default
profile_without_default || build_profile
end
alias_method_chain :profile, :default
end
class Profile < ActiveRecord::Base
belongs_to :user
end
user = User.new
user.profile.something #=> builds a profile for you