Posted almost 10 years ago. Visible to the public.

Properly adding fields with default values to a model

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


Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
Last edit:
about 4 years ago
by Magnus Görlitz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more