Value whitelist using strong parameters in Rails 4

2019-07-19 16:42发布

问题:

Is it possible to use strong parameters to ensure that an attribute will be filtered with a whitelist of possible values?

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?

Thanks

回答1:

Quick answer

No! Strong parameters only let you to filter keys from a hash regardless of the value they have.

Long answer

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