I just put together a plugin that allows you to easily specify default values for AR models. This is useful when your defaults can’t (or you don’t want to) be specified by the database. I use it to populate attribute values from user-configurable defaults. Eg:
class Person < ActiveRecord::Base
defaults :name => ‘My name’, :age => 0
default :country do
Configuration.default_country
end
end
The default values are ignored if the attribute is given a specific value.
You can only define static defaults with migrations. This plugin allows the defaults to be determined when the model object is created. I use this to allow users to implement their own default values.
I’ve just updated the plugin to allow you to do this.
class Person < ActiveRecord::Base
def defaults
# do whatever you like in here
end
end
I could remove the class methods for defining defaults and move to this method of simply having a defaults method on the model. This gives a bit more flexibility, but does make specifying simple defaults for one or two attributes take an extra line or two of code.
class Person < AR
defaults :name => ‘Jonathan’
end
vs
class Person < AR
def defaults
self.name = ‘Jonathan’
end
end