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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)