How to set default values in models? -- in Ruby on Rails 3.1
One approach would be to set the default in your migration. This will be a property that will get set to your database. You can read more here: http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
The other approach is to set a before filter, something like before_save or before_create, and then check if the value on an attribute is nil, you can set it to something.
class Abc
before_save :set_default
protected
def set_default
self.xyz = "default" unless self.xyz
end
end
migration are best for setting default value
write a migration to update column and set default value
self.up do
update_column :table_name,:column_name,:default=>your default value
end
This works well for me
class WorkLogEntry < ActiveRecord::Base
after_initialize do
self.work_done_on ||= Time.zone.today
end
...
end