I've seen docs/websites show that custom validators should go in a /lib
or /lib/validators
directory of a project. I've found (by reading an answer to another post) that they only seem to work in config/initializers
. Does anyone know, or have a pointer to official documentation that shows where custom validators should live?
Where should Rails 3 custom validators be stored?
Asked Answered
How about changing the accepted answer flag? –
Sawdust
If you place your custom validators in app/validators
they will be automatically loaded without needing to alter your config/application.rb
file.
I don't know if there's some gem/config you need to add for this, but under rails 3.2.8 this doesn't work. Specifically, simply dropping your validator into app/validators/???.rb doesn't work. –
Amateur
Doug try to name the validator file same way the validator class is named but underscored: MyCoolValidator goes to app/validators/my_cool_validator.rb –
Elrod
@Amateur you need to restart your server. The autoload paths are expanded on initialization so new subfolders will not get picked up until you do that. –
Aruwimi
I like to also monkeypatch ActiveModel::Validations::HelperMethods to add a helper for my new validation (e.g. validates_address for AddressValidator). When I include both the monkeypatch and the Validator in app/validators/address_validator.rb only the AddressValidator object is loaded, not the monkeypatch. Are you guys experiencing the same behavior? –
Restharrow
spring stop
was necessary for me in Rails 5.2, otherwise it wasn't picked up. –
Secrecy If you add this to your /config/application.rb file:
config.autoload_paths += %W["#{config.root}/lib/validators/"]
Then Rails will automatically load your validators on start up (just like /config/initializers/), but you keep the clean structure of having your validators in one nice, well named spot.
Good idea but your code needs some cleanup:
config.autoload_paths += %W(#{config.root}/lib/validators/)
–
Ridgley lib/validators
seems by far the cleanest. However you may need to load them in before your models, so probably from an initializer.
Here's the official docs about custom validations. AFAIK its a good practice to keep them in the relevant models.
Unless they're applicable to multiple models, in which case you should keep them elsewhere to stay DRY. –
Kwang
Which is what they presumably are because otherwise there's little point in creating a separate class for them. –
Kinser
@Jakub Yes there is: Single Responsibility Principle –
Vicechairman
The link to the official docs is broken. Here is the current location of that documentation; guides.rubyonrails.org/… –
Cyclograph
© 2022 - 2024 — McMap. All rights reserved.