Rhs
Rhs

Reputation: 3318

Rails Validator Skip inclusion

I have a class with the following validators:

fields field:name 'field_name',

requires :field_name,

validates :field_name, inclusion: { in: %w(cat dog fish),
                       message: "%{value} is not a valid field_name"

So I instantiated this class with field_name null and I got two validation errors:

  1. field_name cannot be null (so the requires fails as expected)
  2. null is not a valid field name

Is there a way that I can set up these validators for that if field_name is null, it will skip the second check?

Upvotes: 1

Views: 42

Answers (1)

Pelle
Pelle

Reputation: 6578

Try this:

validates :field_name, inclusion: { in: %w(cat dog fish) },
                       message: "%{value} is not a valid field_name",
                       unless: -> { field_name.nil? }

If you are using ActiveSupport (which you are if you're using Rails), you can also use .blank? instead of .nil? to also treat empty arrays and hashes, and strings with only whitespace as empty.

Upvotes: 1

Related Questions