Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 531
stergosz Avatar asked Aug 21 '12 16:08

stergosz


3 Answers

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 }
like image 60
RadBrad Avatar answered Oct 18 '22 23:10

RadBrad


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.

like image 23
Caleb Hearth Avatar answered Oct 18 '22 21:10

Caleb Hearth


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
like image 12
Yi Zeng Avatar answered Oct 18 '22 21:10

Yi Zeng