Jor*_*ing 26
你将使用验证.这个主题有一个完整的Rails指南.在这种情况下:inclusion,您正在寻找的具体帮助者是,例如:
class Person < ActiveRecord::Base
validates :relationship_status,
:inclusion => { :in => [ 'Single', 'Married', 'Divorced', 'Other' ],
:message => "%{value} is not a valid relationship status" }
end
Run Code Online (Sandbox Code Playgroud)
编辑2015年8月:从Rails 4.1开始,您可以使用enum类方法.它要求您的列是整数类型:
class Person < ActiveRecord::Base
enum relationship_status: [ :single, :married, :divorced, :other ]
end
Run Code Online (Sandbox Code Playgroud)
它也会自动为您定义一些方便的方法:
p = Person.new(relationship_status: :married)
p.married? # => true
p.single? # => false
p.single!
p.single? # => true
Run Code Online (Sandbox Code Playgroud)
您可以在enum此处阅读文档:http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html
| 归档时间: |
|
| 查看次数: |
7777 次 |
| 最近记录: |