Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing or overriding an ActiveRecord validation added by a superclass or mixin

Tags:

I'm using Clearance for authentication in my Rails application. The Clearance::User mixin adds a couple of validations to my User model, but there's one of these that I would like to remove or override. What is the best way of doing this?

The validation in question is

validates_uniqueness_of :email, :case_sensitive => false 

which in itself isn't bad, but I would need to add :scope => :account_id. The problem is that if I add this to my User model

validates_uniqueness_of :email, :scope => :account_id 

I get both validations, and the one Clearance adds is more restrictive than mine, so mine has no effect. I need to make sure that only mine runs. How do I do this?

like image 783
Theo Avatar asked Feb 22 '10 08:02

Theo


1 Answers

I'd fork the GEM and add a simple check, that can then be overridden. My example uses a Concern.

Concern:

module Slugify    extend ActiveSupport::Concern    included do      validates :slug, uniqueness: true, unless: :skip_uniqueness?   end    protected    def skip_uniqueness?     false   end  end 

Model:

class Category < ActiveRecord::Base   include Slugify    belongs_to :section    validates :slug, uniqueness: { scope: :section_id }    protected    def skip_uniqueness?     true   end end 
like image 175
kim3er Avatar answered Oct 23 '22 11:10

kim3er