I want to create a default value for an attribute by defining it in ActiveRecord. By default everytime the record is created, I want to have a default value for attribute :status
. I tried to do this:
class Task < ActiveRecord::Base
def status=(status)
status = 'P'
write_attribute(:status, status)
end
end
But upon creation I still retrieve this error from the database:
ActiveRecord::StatementInvalid: Mysql::Error: Column 'status' cannot be null
Therefore I presume the value was not applied to the attribute.
What would be the elegant way to do this in Rails?
Many thanks.
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