0

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.

gbright
  • 57
  • 6
  • Possible duplicate of [rails validation: :allow\_nil and :inclusion both needed at the same time](https://stackoverflow.com/questions/17359853/rails-validation-allow-nil-and-inclusion-both-needed-at-the-same-time) – Brad Werth Sep 18 '17 at 15:55
  • Also possibly at https://stackoverflow.com/questions/26770359/rails-4-validation-where-to-put-the-allow-nil-when-doing-an-inclusion, https://stackoverflow.com/questions/13465691/validate-on-inclusion-within-array-of-options-or-be-nil, and https://stackoverflow.com/questions/26770359/rails-4-validation-where-to-put-the-allow-nil-when-doing-an-inclusion/26770493. – Brad Werth Sep 18 '17 at 15:57

1 Answers1

0

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.

gbright
  • 57
  • 6