Ask A Question

Notifications

You’re not receiving notifications from this thread.

Normalizes method in ActiveRecord Discussion

I would like to add that you can add multiple attributes to be normalized

normalizes [:phone:, :fax, :mobile], with: -> phone_number { phone_number.gsub(/\D/, '') }
Reply

Superb

Reply

This is a great feature.

The greatest disadvantage is, that it only works with ActiveRecord and not with ActiveModel.
This means you cannot use it for Form Objects or other, non-ActiveRecord-baked classes.
I opened a feature request. Hopefully, it will be migrated to ActiveModel some day.
See https://discuss.rubyonrails.org/t/proposal-activemodel-normalization/85405

I also wrote a small blog post about how to increase reusability and testability of this.
See https://tobiasmaier.info/posts/2024/03/24/reusability-for-active-record-normalize.html

This would lead to the introduction of normalization pipelines:

class User < ActiveRecord::Base
  normalizes :email, with: PipelineNormalizer.new(StripNormalizer, BlankNormalizer, -> { _1&.downcase })
end
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.