简体   繁体   English

Rails迁移中的默认值的常量

[英]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. 我刚刚开始使用Rails并决定制作一个小应用程序来学习实用的东西。

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. 我想使用常量添加到迁移a:默认值。

In my user model I defined the different groups with constants so that I can later easily check "admin?" 在我的用户模型中,我使用常量定义了不同的组,以便稍后我可以轻松地检查“admin?” etc. 等等

t.integer :user_group, :default => USER

I get the following error on db:migrate 我在db:migrate上收到以下错误

rake aborted! 耙子流产了! Expected [...]/app/models/user.rb to define USER 期望[...] / app / models / user.rb定义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: 如果您的类名为User ,请尝试以下操作:

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 ? 我错了吗 ?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM