Search code examples
ruby-on-railsvalidationrubygemsmonkeypatchingacts-as-taggable-on

Adding a scope to ruby gem validation of uniqueness


acts-as-taggable-on gem has a built-in uniqueness validation:

validates_uniqueness_of :name, if: :validates_name_uniqueness?

def validates_name_uniqueness?
  true
end

How do I add a scope to this validation?

I want to add scope: :user_id and don't know how to edit a gem source code.


Solution

  • I was able to fix my problem with the help of acts_as_taggable_on.rb file in config/initializers:

    module ActsAsTaggableOn
      class Tag < ::ActiveRecord::Base
        Tag.class_eval do
          _validators.reject!{ |key, _| key == :name }
    
          _validate_callbacks.each do |callback|
            callback.raw_filter.attributes.delete :name if callback.raw_filter.is_a?(ActiveRecord::Validations::UniquenessValidator)
          end
          validates_uniqueness_of :name, scope: :user_id
        end
      end
    end