Sha256: eb7a6bea2c367dcc6091c66f7ac33d05514ed54d05ebb64379eaa53d4daa51f0

Contents?: true

Size: 1.55 KB

Versions: 19

Compression:

Stored size: 1.55 KB

Contents

module ActiveModel
  module Validations
    class OwnershipValidator < EachValidator
      def validate_each(record, attribute, value)
        owner = record.send(options[:with])
        actual_owner = value ? value.send(options[:with]) : nil

        if value && owner != actual_owner
          record.errors.add(
            attribute, :invalid_owner,
            :message => options[:message]
          )
        end
      end

      def check_validity!
        raise ArgumentError, ":with is required" unless options.key?(:with)
        raise ArgumentError, ":with option must be a string or a symbol" unless ["String", "Symbol"].include?(options[:with].class.name)
      end
    end

    module ClassMethods
      # Validates whether the owner of the specified attribute is the same from the current object.
      #
      #   class Task < ActiveRecord::Base
      #     belongs_to :user
      #     belongs_to :category
      #
      #     validates_ownership_of :category, :with => :user
      #   end
      #
      #   user = User.find(1)
      #   another_user = User.find(2)
      #
      #   user_category = user.categories.first
      #   another_user_category = another_user.categories.first
      #
      #   task = user.tasks.create(:category => user_category)
      #   task.valid?
      #   #=> true
      #
      #   task = user.tasks.create(:category => another_user_category)
      #   task.valid?
      #   #=> false
      #
      def validates_ownership_of(*attr_names)
        validates_with OwnershipValidator, _merge_attributes(attr_names)
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
validators-2.7.0 lib/validators/validates_ownership_of.rb
validators-2.6.0 lib/validators/validates_ownership_of.rb
validators-2.5.4 lib/validators/validates_ownership_of.rb
validators-2.5.3 lib/validators/validates_ownership_of.rb
validators-2.5.2 lib/validators/validates_ownership_of.rb
validators-2.5.1 lib/validators/validates_ownership_of.rb
validators-2.5.0 lib/validators/validates_ownership_of.rb
validators-2.4.2 lib/validators/validates_ownership_of.rb
validators-2.4.1 lib/validators/validates_ownership_of.rb
validators-2.4.0 lib/validators/validates_ownership_of.rb
validators-2.3.0 lib/validators/validates_ownership_of.rb
validators-2.2.0 lib/validators/validates_ownership_of.rb
validators-2.1.0 lib/validators/validates_ownership_of.rb
validators-2.0.0 lib/validators/validates_ownership_of.rb
validators-1.0.0 lib/validators/validates_ownership_of.rb
validators-0.1.3 lib/validators/validates_ownership_of.rb
validators-0.1.2 lib/validators/validates_ownership_of.rb
validators-0.1.1 lib/validators/validates_ownership_of.rb
validators-0.1.0 lib/validators/validates_ownership_of.rb