Properly adding fields with default values to a model

We're now OK with defining defaults in either the model or the database.

When adding a new field to your model's database table, don't set any defaults in the database.

It makes people wonder why they get such values when reading attributes.\
Why? Because nobody looks at the database layout since such things are part of your application's logic -- and thus they belong into the corresponding model.

How to

Do it like this:

  • In your migration, after adding the field, update all fields to your desired default:

    update "UPDATE users SET locked = #{quoted_false};"
    
  • In your model, set a default value. For boolean attributes, simply use the attached flag trait:

    does 'flag', :locked, :default => false
    

The flag trait makes sure the field is set to the default on new records and adds a validation for it to only be true or false.
In those rare cases where nil is okay for you, pass :allow_nil => true to the trait.

For non-boolean attributes

Apply that process to "regular" attributes as well.

  • Do the migration alike
  • Use has_defaults in your model

Requirements

Arne Hartherz Over 12 years ago