Read more

Properly adding fields with default values to a model

Arne Hartherz
October 07, 2011Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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

Posted by Arne Hartherz to makandra dev (2011-10-07 14:08)