38

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

3 Answers 3

58

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 }
Sign up to request clarification or add additional context in comments.

1 Comment

For the record, you can use type if you put self.inheritance_column = nil in the model, or in ApplicationRecord if you don't use Single Table Inheritance (STI) at all. We don't use STI (and don't generally recommend it under most circumstances) so that's what we do and appreciate not having to prefix our "type" columns with something.
24

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.

2 Comments

While this works, it leads to a rubocop offence: RuboCop: Prefer the new style validations validates :column, inclusion: value over validates_inclusion_of. [Rails/Validation]
Potential edit: Rails now offers the ability to override the STI table via inheritance column.
17

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.
  • In favor of %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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.