加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何限制列的值

发布时间:2020-12-16 22:29:42 所属栏目:百科 来源:网络整理
导读:我想限制字段的可用值.因此列的值必须来自指定的值集合.是否可能使用迁移/模型?或者我必须手动在我的数据库? 解决方法 您将使用验证.这是 a whole Rails guide on the topic.在这种情况下,你正在寻找的具体帮手是 :inclusion ,例如: class Person ActiveR
我想限制字段的可用值.因此列的值必须来自指定的值集合.是否可能使用迁移/模型?或者我必须手动在我的数据库?

解决方法

您将使用验证.这是 a whole Rails guide on the topic.在这种情况下,你正在寻找的具体帮手是 :inclusion,例如:
class Person < ActiveRecord::Base
  validates :relationship_status,:inclusion  => { :in => [ 'Single','Married','Divorced','Other' ],:message    => "%{value} is not a valid relationship status" }
end

编辑2015年8月:从Rails 4.1开始,您可以使用枚举类方法.它需要您的列为整数类型:

class Person < ActiveRecord::Base
  enum relationship_status: [ :single,:married,:divorced,:other ]
end

它也会自动为您定义一些方便的方法:

p = Person.new(relationship_status: :married)

p.married? # => true
p.single? # => false

p.single!
p.single? # => true

您可以在这里阅读枚举文档:http://api.rubyonrails.org/v4.1.0/classes/ActiveRecord/Enum.html

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读