Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Rails attribute presence but allow empty string

I want to validate a string attribute is not nil, but allow empty strings.

As in:

validates name: not_nil, allow_empty: true
like image 469
James Bush Avatar asked May 02 '18 23:05

James Bush


People also ask

What is the difference between validate and validates in rails?

So remember folks, validates is for Rails validators (and custom validator classes ending with Validator if that's what you're into), and validate is for your custom validator methods.

How do I bypass validation?

A very common way to skip validation is by keeping the value for immediate attribute as 'true' for the UIComponents. Immediate attribute allow processing of components to move up to the Apply Request Values phase of the lifecycle. scenario: While canceling a specific action, system should not perform the validation.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


2 Answers

you could also do:

validates :name, exclusion: { in: [nil] }
like image 84
NullVoxPopuli Avatar answered Sep 19 '22 10:09

NullVoxPopuli


To allow an empty string, but reject nil in an active record validation callback, use a conditional proc to conditionally require the presence of the attribute if it's not nil.

So the code looks like:

validates :name, presence: true, if: proc { name.nil? }

But you probably want to allow null. Then don't validate. Still check for presence? in code for nil or empty string.

like image 30
James Bush Avatar answered Sep 20 '22 10:09

James Bush