Hop*_*eam 20 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1
我在名为user的模型中有一个字段类型,它是db中的int.int的值指定它的存储类型.例:
我有其他几个这样的领域,所以创建关联表是过分的.
不是在模型和控制器逻辑中的条件语句中检查那些int值,而是在rails中存在这些常量来存储这些常量.
所以我可以从模型和控制器中做到这一点?
if myuser.type == MOM
elsif myuser.type == GRAND_MOTHER
Run Code Online (Sandbox Code Playgroud)
编辑:解决方案我最后一起去了:
在模型中:
# constants
TYPES = {
:mom => 0,
:dad => 1,
:grandmother => 2,
:grandfather => 3
}
Run Code Online (Sandbox Code Playgroud)
在逻辑上:
if u.type == User::TYPES[:mom]
Run Code Online (Sandbox Code Playgroud)
即使它更长,我觉得当他们阅读我的代码时,对其他开发人员来说更直观.感谢下面的Taro这个解决方案.
tar*_*aro 40
就像是:
class User < ActiveRecord::Base
TYPES = %w{ mom dad grandmother grandfather son }
TYPES.each_with_index do |meth, index|
define_method("#{meth}?") { type == index }
end
end
u = User.new
u.type = 4
u.mom? # => false
u.son? # => true
Run Code Online (Sandbox Code Playgroud)
Oll*_*ett 10
从Rails 4.1开始,支持ActiveRecord :: Enum.
有一个有用的教程在这里,但是在短:
# models/user.rb
class User < ActiveRecord::Base
enum family_role: [ :mum, :dad, :grandmother]
end
# logic elsewhere
u = User.first
u.family_role = 'mum'
u.mum? # => true
u.family_role # => 'mum'
Run Code Online (Sandbox Code Playgroud)
注意:要从当前方案(数据库已存储与值对应的数字)进行转换,应使用哈希语法:
enum family_role: { mum: 0, dad: 1, grandmother: 2 }
Run Code Online (Sandbox Code Playgroud)
我还建议您保留0
默认状态,但这只是一个约定而不是关键.