Strip attributes via before_save, not just before_validation#83
Strip attributes via before_save, not just before_validation#83knagode wants to merge 2 commits intormm5t:masterfrom
Conversation
|
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 |
|
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. |
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.