Rails put validation in a module mixin? Rails put validation in a module mixin? ruby ruby

Rails put validation in a module mixin?


module Validations  extend ActiveSupport::Concern  included do    validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true    validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true  endend

The validates macro must be evaluated in the context of the includer, not of the module (like you probably were doing).


Your module should look something like this:

module CommonValidations  extend ActiveSupport::Concern  included do    validates :name, :length => { :minimum => 2 }, :presence => true, :uniqueness => true    validates :name_seo, :length => { :minimum => 2 }, :presence => true, :uniqueness => true  endend

Then in your model:

class Post < ActiveRecord::Base  include CommonValidations  ...end

I'm using ActiveSupport::Concern here to make the code a little clearer.