开发者

A constant for a default value in Rails migration

开发者 https://www.devze.com 2023-01-31 21:55 出处:网络
I\'m just starting with Rails and 开发者_开发知识库decided to make a small app to learn with something practical.

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.


I think you can also write :

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

Am i wrong ?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号