Constant for default in Rails migration

I am just starting out with Rails and decided to make a small application to learn something practical.

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

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

t.integer :user_group, :default => USER 

I get the following error on db: migrate

rake is interrupted! Expected [...] / app / models / user.rb to determine USER

However, in the user model, I have this:

 ADMIN = 1 USER = 2 

Any ideas what I'm doing wrong?

+6
ruby-on-rails
source share
3 answers

When referencing a constant, you must specify the name of your class. If your class is named User , try the following:

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

or

 t.integer :user_group, :default => User::ADMIN 
+4
source share

You cannot use a constant in migration, since migration must be an independent point in time. Migration should not be combined with a code base that can change over time, since the migration would then change depending on when you started it. If you or someone else changes the value of the constant in the code base (later), this will affect the transfer. It may not be entirely realistic that you really need to change the constant value in the code, but this is just an argument from the principle.

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

+1
source share

I think you can also write:

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

I am wrong?

0
source share

All Articles