Rails: How do I create a default value for attributes in Rails activerecord’s model? [duplicate]

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.

10 Answers
10

Leave a Comment