Rails: How do I create a default value for attributes in Rails activerecord's model? [duplicate]
You can set a default option for the column in the migration
....
add_column :status, :string, :default => "P"
....
OR
You can use a callback, before_save
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
end
end
Because I encountered this issue just a little while ago, and the options for Rails 3.0 are a bit different, I'll provide another answer to this question.
In Rails 3.0 you want to do something like this:
class MyModel < ActiveRecord::Base
after_initialize :default_values
private
def default_values
self.name ||= "default value"
end
end
When I need default values its usually for new records before the new action's view is rendered. The following method will set the default values for only new records so that they are available when rendering forms. before_save
and before_create
are too late and will not work if you want default values to show up in input fields.
after_initialize do
if self.new_record?
# values will be available for new record forms.
self.status = 'P'
self.featured = true
end
end