bakineggs

least surprising surprise

My name is Dan Barry aka bakineggs.

I like code.

I'm writing a language called Bonsai.

I work at Square.

Blog

October 14, 2011 @ 2:58am

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

Post Comment

© 2008-2013 Dan Barry. Designed by Hunter Hastings.