Reputation: 3318
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:
null
(so the requires
fails as expected)null
is not a valid field nameIs 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
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