Rails 4 中使用强参数的值白名单 [英] Value whitelist using strong parameters in Rails 4
本文介绍了Rails 4 中使用强参数的值白名单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以使用强参数来确保使用可能值的白名单过滤属性?
Is it possible to use strong parameters to ensure that an attribute will be filtered with a whitelist of possible values?
例如,我有一个参数 age,我想确保它只能有这个值 [10,20,30,40,50].是否可以使用强参数逻辑来确保?
For example, I have a parameter age that I want to ensure that can only have this values [10,20,30,40,50]. Is it possible to use the strong parameters logic to ensure that?
谢谢
推荐答案
快速解答
不!强参数只允许您从散列中过滤键,而不管它们的值如何.
No! Strong parameters only let you to filter keys from a hash regardless of the value they have.
长答案
不!但正如评论中指出的那样,您最好的解决方案是使用 validations:>
No! But as it was pointed out in comments, your best solution is to use validations:
class MyModel < ActiveRecord::Base
validates :value, inclusion: { in: [1,2,3] }
end
这篇关于Rails 4 中使用强参数的值白名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文