Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork59
Strip attributes via before_save, not just before_validation#83
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
base:master
Are you sure you want to change the base?
Strip attributes via before_save, not just before_validation#83
Uh oh!
There was an error while loading.Please reload this page.
Conversation
rmm5t commentedSep 11, 2025
I think I'd like to consider moving strip_attributes to use the However, this will likely require Rails 8.1 (rails/rails#53887) In the meantime, redefining If I incorporated this |
knagode commentedSep 12, 2025
I added code to ensure that stripping normalization isn’t executed twice. I didn’t add a test, as I don’t think it’s necessary, but I’m happy to add one if you think it’s worth it before merging. I can confirm that this PR would prevent several issues on our side but I understand that not many people use If we were already on Rails 8.1, I’d probably just replace the strip_attributes operation with Rails’ built-in normalize. |
Uh oh!
There was an error while loading.Please reload this page.
It is often very handy to use
.save(validate: false), for example when allowing users to save drafts.I noticed (too late) that strip_attributes only strips attributes before validation. My expectation was that it would always convert
''toNULL. Because it didn’t, I ended up with many empty string values in the database, which caused unique index exceptions (''behaves very differently fromNULLwhen dealing with unique indexes, and I wanted to ensure that empty strings are never persisted).I believe strip_attributes should also work when using .save(validate: false), or at least provide a configurable setting to enable this behaviour by default across all models.
Workaround: call
.valid?before.save(validate: false). This works, but it doesn’t feel intuitive.