Reputation: 153
I want to validate a string attribute is not nil, but allow empty strings.
As in:
validates name: not_nil, allow_empty: true
Upvotes: 10
Views: 8027
Reputation: 948
Alternatively
validates :name, presence: true, allow_blank: true
Upvotes: -2
Reputation: 153
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.
Upvotes: 4
Reputation: 65183
you could also do:
validates :name, exclusion: { in: [nil] }
Upvotes: 8