stergosz
stergosz

Reputation: 5860

rails validate in model that value is inside array

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

Upvotes: 37

Views: 29747

Answers (3)

Yi Zeng
Yi Zeng

Reputation: 32855

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

Upvotes: 17

Caleb Hearth
Caleb Hearth

Reputation: 3365

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.

Upvotes: 24

RadBrad
RadBrad

Reputation: 7304

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 }

Upvotes: 57

Related Questions