Ask A Question

Notifications

You’re not receiving notifications from this thread.

How to Build Custom ActiveRecord Validations Discussion

How does "resizable_image: true" work? I'm assuming that because you named your validator "resizable_image_validator.rb" with a class name "ResizableImageValidator" and then calling "validates :avatar, resizable_image: true" that rails is just doing some magic here.

Is that correct? How else would your user model know where to find ResizableImageValidator ? That wasn't really clear to me in the vid.

Reply

Lee McAlilly,

Yes, that's correct. Refer to this "Active Model Validator API" here https://edgeapi.rubyonrails.org/classes/ActiveModel/Validator.html

While adding our own custom validation for an attribute, we need to create a subclass of ActiveModel::EachValidator and implement the "validate_each" method.

Once we create a new class, for example above "ResizableImageValidator" with the file name as resizable_image_validator.rb, the Rails fw convention will take care of adding this as a custom validator in the validation chain. Generally, when files are kept in the Rails "app" folder, it will be autoloader, and hence that custom validator is also available on app load. You may also refer to this discussion here https://gorails.com/forum/where-do-i-put-a-custom-validator-for-a-model

Reply

Thanks a lot for info! It s really interesting

Reply

this is awesome

Reply
Join the discussion
Create an account Log in

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

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

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

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more.

    © 2024 GoRails, LLC. All rights reserved.