rails validate in model that value is inside array rails validate in model that value is inside array arrays arrays

rails validate in model that value is inside array


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.
  • 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