I want to validate a string attribute is not nil, but allow empty strings.
As in:
validates name: not_nil, allow_empty: true
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.
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.
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.
you could also do:
validates :name, exclusion: { in: [nil] }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With