Rails 使用带有表单和数组的数组验证包含 [英] Rails using arrays with forms & validation inclusion of

查看:43
本文介绍了Rails 使用带有表单和数组的数组验证包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试就使用数组进行表单选择但使用相同的数组来测试是否包含用于验证的最佳方法获得一些好的建议.

Trying to get some good advice on the best approach to using arrays for form select but using the same array to test inclusion of for the validation.

现在我有了它,但在元素和验证中构建数组,即,

Right now I have it but building the arrays within the elements and validation ie,

# Form
<%= f.select(:status, [['Live','live'], ['Paused', 'paused']]) %>

# Model
validates :status, :inclusion => { :in => %w(live paused) }

我相信会有更好的方法来存储和使用这些数组!

I'm sure there would be a better way to store these arrays and use them !

感谢您提供的任何建议.

Thanks for any advise you can provide.

推荐答案

您可以将这两个常量添加到您的模型中,然后调用验证:

You can add these two constants to your model and then call the validation:

VALID_STATES = ["live", "paused"]
SELECT_STATES = VALID_STATES.map { |s| [s.capitalize, s] }
validates :status, :inclusion => { :in => Model::VALID_STATES }

这篇关于Rails 使用带有表单和数组的数组验证包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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