如何在 rails 中指定和验证枚举? [英] How do i specify and validate an enum in rails?

查看:61
本文介绍了如何在 rails 中指定和验证枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个模型Attend,它将有一个状态列,而这个状态列只有几个值.STATUS_OPTIONS = {:yes, :no, :maybe}

I currently have a model Attend that will have a status column, and this status column will only have a few values for it. STATUS_OPTIONS = {:yes, :no, :maybe}

1) 我不确定如何在用户插入出席之前验证这一点?基本上是 java 中的枚举,但我怎么能在 Rails 中做到这一点?

1) I am not sure how i can validate this before a user inserts an Attend? Basically an enum in java but how could i do this in rails?

推荐答案

创建您想要的选项的全局可访问数组,然后验证您的状态列的值:

Create a globally accessible array of the options you want, then validate the value of your status column:

class Attend < ActiveRecord::Base

  STATUS_OPTIONS = %w(yes no maybe)

  validates :status, :inclusion => {:in => STATUS_OPTIONS}

end

然后您可以通过 Attend::STATUS_OPTIONS

这篇关于如何在 rails 中指定和验证枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆