1

My User model looks similar to this:

class User < ActiveRecord::Base
  enum type: [:admin, :reviewer, :super_admin ]
  validates :type, presence: true
  validates :type, inclusion: { in: User.types.keys }
end

When I submit anything outside the enum values, the validation doesn't stop the code from running, and I get a 500 error as a response with the following error:

'something submitted' is not a valid type

If I submit a blank field, the validation works:

"type": [
    "can't be blank",
    "is not included in the list"
]

What am I doing wrong? My code looks identical to this answer

Community
  • 1
  • 1
Sebastian
  • 2,154
  • 1
  • 26
  • 42

1 Answers1

1

Rails enum doesn't have in-built validation.

The current focus of AR enums is to map a set of states (labels) to an integer for performance reasons. Currently assigning a wrong state is considered an application level error and not a user input error. That's why you get an ArgumentError.

You still can set nil or an empty string to the enum attribute without raising an error.

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
  • Thanks. What would be considered best practice for this case? Having a user_types table and a User.type_id foreign key attribute? – Sebastian Jun 17 '15 at 15:52
  • @Vasile sorry but i cant' give you **the best suggestion**, i don't know what a task you tried to resolve. Give me a full picture =) – Roman Kiselenko Jun 17 '15 at 15:57
  • I've got three types of users, an admin can add a user through a submit form. There's going to be a drop-down with the user type, but I just wanted to make sure it's validated server-side as well. It seems weird that you can't validate a value to be part of an array. – Sebastian Jun 17 '15 at 16:07
  • there is a gem that adds a validator over specified enum attributes. this will add active model error message over attributes instead of raising errors. https://github.com/CristiRazvi/enum_attributes_validation – cristi_razvi Feb 12 '18 at 07:30