Sha256: 848ea8f9fa4f9777eb2f7c39995e27900119e93f399413771aaf1efb85bb1895
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).to_a.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.5 | lib/activeform-rails/validate_uniqueness.rb |