Default
value is set in database.
When you try to insert a record in people
table with status
attribute set as nil
, only then the default value normal
would be inserted in the database against status
column.
If you are not passing any value to status
attribute while saving a new record, its value would be nil. Hence, the validation won't pass. Status
would only be set to "normal" at the time of inserting the record.
I would suggest you to modify the model as below, database would take care of the default value:
class Person < ActiveRecord::Base
validates_inclusion_of :status, in: [ "super" ], allow_nil: true
end
Or
Second option would be, as Danny suggested, set up an after_initialize callback and set the default value of status
when its not specified. If you take up this option then I don't think that you need a default value at DB level as it status field would always be set from Model.
class Person < ActiveRecord::Base
after_initialize :init_status, if: :new_record?
validates_inclusion_of :status, in: [ "normal","super" ]
def init_status
self.status ||= "normal"
end
end