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

User.new.age   # => 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|
    model.name = "Drone for #{model.organization.name}"
  end
end

evil_organization.name  # => "Evil Organization"
user = evil_organization.users.create
user.name               # => "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.

  • Please feel free to file a bug describing the issue you’re having with Rails 3.1 and I will try to look into it. (I’m the guy who rewrote the associations code in 3.1…)

  • BSM

    Check out https://github.com/bsm/attribute-defaults. It’s inspired by default_value_for but has additional features.