bakineggs

rubies rock your rails

My name is Dan Barry. I've been a programming enthusiast for over ten years now.

Professionally, I've been developing web applications using Ruby on Rails. For fun, I'm writing a language called okk.

I'm currently living in San Francisco, California where I work as a software engineer 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-2012 Dan Barry. Designed by Hunter Hastings.