In RoR 3.1, "validates" still doesn't have a way of setting default values in the models. Or is there? If not, what's the best way to set default values?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With