-
Notifications
You must be signed in to change notification settings - Fork 21.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
allow_nil
and allow_blank
do not work correctly with defaulted attribute accessors
#37007
Comments
allow_blank
and allow_empty
don't work correctly with defaulted attribute accessorsallow_blank
does not work correctly with defaulted attribute accessors
allow_blank
does not work correctly with defaulted attribute accessorsallow_nil
and allow_blank
do not work correctly with defaulted attribute accessors
A workaround for me is to not use |
@aardvarkk, I have this patched on one of my projects. Do you mind if I make a PR for it? |
Go for it @joshmn ! This issue didn't get any response, so I assumed maybe I was crazy or nobody else thought this was a problem. |
Hello Firstly, I tried your example with validates :bar, numericality: { greater_than: 100 }, allow_blank: true But this didn't work either because ActiveRecord seems to cast def test_validation
foo = Foo.new
foo[:bar] = ''
puts foo[:bar].class
# NilClass
foo[:bar] = 'bar'
puts foo[:bar]
# 0
end Before the numericality validition runs, def bar
self[:bar] || 123
end which in this case always returns What confused me is that Then I found that class Foo < ActiveRecord::Base
validates :bar, numericality: { greater_than: 100 }, allow_blank: true
def bar
self[:bar] || 123
end
def read_attribute_for_validation(key)
self[key]
end
end But in my opinion this might have a downside, since this "rule" is then applied to all validations, which may have side effects again... so eventually you could use this validation instead: validates :bar, numericality: { greater_than: 100 }, unless: -> { self[:bar].blank? } I hope I did my research accurately... 😉 |
This issue has been automatically marked as stale because it has not been commented on for at least three months. |
Steps to reproduce
allow_nil
/allow_blank
end up being checked against the defaulted accessorExpected behavior
foo
should be valid since blank values are allowedActual behavior
foo
is invalid, I believe due to the fact that allow_blank is checked against the defaulted value, and once numericality is checked on the raw value the blank string is not a proper number so a validation error occurs.System configuration
Rails version:
master
(6.1.0 alpha), but I first noticed the issue in Rails v5.2.3Ruby version:
2.6.3
The text was updated successfully, but these errors were encountered: