Rails: validation that spans multiple models, where to put it?
I have a custom validation method that is exactly the same开发者_高级运维 for two or more models. Where's the best place to put this validation method so that both models can access it and keep things DRY? If the validation fails, I also want to use errors.add_to_base, so wherever this method is put, I should be able to accommodate for that.
Create a module in your lib directory and then include it in. You can also create a parent class from which your models inherit and put it there, but that seems a bit over the top for something that simple.
The best practice is to create a custom validator that extends ActiveModel::EachValidator
(if an attribute validation) or ActiveModel::Validator
if it's a bit more complex.
class DomainNameValidator < ActiveModel::EachValidator
That file should reside in app/validators/contact_address_validator
to be auto-loaded by rails. Each class that needs that validator could specify
validates :name, uniqueness: true, domain_name: true
where the key part is domain_name: true
. The _validator
is not needed. As you can see, your custom validator can be combined with other Rails built-in validators.
精彩评论