Sha256: de497df0e889215e1da815bf32d93b841742c565993c55d81f9adcf6741d0d0b

Contents?: true

Size: 1.02 KB

Versions: 1

Compression:

Stored size: 1.02 KB

Contents

module ActiveForm
  module ValidateUniqueness
    def self.included(base)
      base.class_eval do
        extend ClassMethods
      end
    end

    module ClassMethods
      def validates_uniqueness_of(attribute, model_name, options = {})
        validates_each attribute, options do |form, attr, value|
          @form = form
          @model = form.send(model_name)
          @klass = @model.class
          @hash = { attribute => value }
          add_error_message(attribute) if another_model?
        end
      end

      private

      def another_model?
        @model.persisted? ? another_model_without_itself : any_model?
      end

      def another_model_without_itself
        @klass.where(@hash).delete_if { |m| m.id == @model.id }.count >= 1
      end

      def any_model?
        @klass.exists?(@hash)
      end

      def error_message
        I18n.t('activerecord.errors.messages.exclusion')
      end

      def add_error_message(attribute)
        @form.errors.add(attribute, error_message)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
activeform-rails-0.0.4 lib/activeform-rails/validate_uniqueness.rb