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?

Reply

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.

Reply

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?

Reply

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

Reply

My little experience is that app/validators makes it easier to import the custom validator in the model than using app/models/validators as with the first one there is no need to user include my_custom_validator in the model.

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.