Search code examples
ruby-on-railsvalidationinclusion

Rails validation: Get rid of the invalid value message for nil when using an inclusion validator while still preventing nil from being saved


Given validation on a field such as the following:

validates :entity_type, inclusion: { in: %w(1 2), message: "is invalid" }

The error messages that will be returned if the user enters nil for the field are

“can’t be blank”, ” is invalid”

How can this validation be changed so that only 'can't be blank' is returned if nil is the entered value for the field?

This is a case where we don't want nil to be a valid value, just to clean up the validation messaging.


Solution

  • I haven't seen any documentation on this anywhere so wanted to give an answer.

    The answer is to use allow_nil: true with the inclusion validator.

    validates :entity_type, inclusion: { in: %w(1 2), message: "is invalid" }, allow_nil: true

    Using this means if a nil value is given for the field, only the 'can't be blank' message will be returned from the validator, while non-nil invalid values will continue to work as normal.