Rails Validations and the DRY principle

I have 9 different models, all with a column called 'name'. In each model I have the following validation:

validates :name, presence: true, uniqueness: true

To adhere to the DRY principle, should that validation go in a parent class and have my models that use that validation inherit from the parent class?

1 Answer

  1. Lorin- Reply


    You could try using a name validation concern instead. That way if you ever want to change the validation you only have to do it in one place, without having to create subclasses of something with model behaviour that isn't actually a model.

    You can read how to use Concerns here http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>