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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With