Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
zbrox Avatar asked Dec 24 '10 12:12

zbrox


2 Answers

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
like image 108
Brett Bender Avatar answered Nov 18 '22 09:11

Brett Bender


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.

like image 20
Magne Avatar answered Nov 18 '22 08:11

Magne