I have a form where i pass a field named :type and i want to check if it's value is inside an array of allowed types so that no one is allowed to post not-allowed types.
the array looks like
@allowed_types = [
   'type1',
   'type2',
   'type3',
   'type4',
   'type5',
   'type6',
   'type7',
   etc...
]
i have tried using validates_exclusion_of or validates_inclusion_of but it doesn't seem to work
first, change the attribute from type to something else, type is a reserved attrubute name use for Single Table Inheritance and such.
class Thing < ActiveRecord::Base
   validates :mytype, :inclusion=> { :in => @allowed_types }
                        ActiveModel::Validations provides a helper method for this. An example call would be:
validates_inclusion_of :type, in: @allowed_types
ActiveRecord::Base is already a ActiveModel::Validations, so there is no need to include anything.
http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of
Also, @RadBrad is correct that you should not use type as a column name as it is reserved for STI.
Just for those lazy people (like me) to copy the latest syntax:
validates :status, inclusion: %w[pending processing succeeded failed]
validates_inclusion_of is out of date since Rails 3.:inclusion=> hash syntax is out of date since Ruby 2.0.%w for word array as the default Rubocop option.With variations:
Default types as a constant:
STATUSES = %w[pending processing succeeded failed]
validates :status, inclusion: STATUSES
OP's original:
validates :mytype, inclusion: @allowed_types
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With