zbrox
zbrox

Reputation: 2723

A constant for a default value in Rails migration

I'm just starting with Rails and decided to make a small app to learn with something practical.

I have a user class which has a user group integer field. I want to add to the migration a :default value using a constant.

In my user model I defined the different groups with constants so that I can later easily check "admin?" etc.

t.integer :user_group, :default => USER

I get the following error on db:migrate

rake aborted! Expected [...]/app/models/user.rb to define USER

However in the user model I have this:

ADMIN = 1
USER = 2

Any ideas what I'm doing wrong?

Upvotes: 7

Views: 1945

Answers (3)

Magne
Magne

Reputation: 17223

You shouldn't use a constant in a migration, since the migration should represent an independent point in time. A migration should not be coupled to a codebase which could change over time, since the migration then would change depending on when you run it. If you or someone else changes the value of the constant in the codebase (later on), it would impact the migration. It might not be realistic that you would actually ever need to change the constant value in the code, but this is merely an argument from principle.

If you want to change the default value in the DB at a later point in time, then just make a new migration then, with a new value.

Upvotes: 4

babttz
babttz

Reputation: 466

I think you can also write :

t.integer :User, :user_group, :default => ADMIN

Am i wrong ?

Upvotes: 0

Brett Bender
Brett Bender

Reputation: 19738

You need to include your class name when referencing your constant. If your class is named User, try this:

t.integer :user_group, :default => User::USER

or

t.integer :user_group, :default => User::ADMIN

Upvotes: 5

Related Questions