All threads / Where do I put a custom validator for a model?

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Where do I put a custom validator for a model?

Fernando Flores asked in Databases

I'm confused about where to put code for a custom validator I wrote, should I create a nested class inside the model file? or create a new file in models/concerns? I have the code but don't know where is the right place to put the file, can someone help me please?

Any folders in app/ will be autoloaded, so you could create app/validators/my_validator.rb and include MyValidator in your model. Rails will autoload that and find it correctly. This is my preferred way of doing things usually.

Or you could put it in lib and require it as well.

Thank you Chris, so I guess it be ok if I put it inside the concerns folder. One more thing should it be a module or just a class definition?

Generally, the concerns folder is for modules so it might get confusing in there but it should work.

You could also probably use app/models/validators/my_validator and include Validators::MyValidator now that I think about it.

I like this better than app/validators

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2021 GoRails, LLC. All rights reserved.