Phusion white papers Phusion overview

Phusion Blog

default_value_for 1.0.5 released: default attribute values for ActiveRecord models

By Hongli Lai on August 10th, 2011

We’ve just released default_value_for version 1.0.5. default_value_for is a Rails plugin for supporting default values in ActiveRecord models. Like this:

class User < ActiveRecord::Base
  default_value_for :age, 10
end   # => 10

You can read more about this plugin at Github.

Version 1.0.5 fixes support for Rails 3.0 and Rails 3.1. Unfortunately we had to remove one feature due to changes in ActiveRecord 3.1. It is no longer possible to access associations in the default_value_for_block. The following is no longer possible:

class User < ActiveRecord::Base
  belongs_to :organization
  default_value_for :name do |model| = "Drone for #{}"
end  # => "Evil Organization"
user = evil_organization.users.create               # => "Drone for Evil Organization"??

One would expect the last expression to evaluate to “Drone for Evil Organization”. On Rails 2 and Rails 3.0, it does, but on Rails 3.1 it does not. Because of the way the ‘organization’ attribute is assigned to the model by ActiveRecord, we are no longer able to support this behavior. Inside the default_value_for block, model.organization would evaluate to nil.