Sha256: 1e55422e5fe575473659fca1e0e9313387f8e95b6ff0294a935f5ea5a8d59375

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

module UnscopedAssociations

  def self.included(base)
    base.extend ClassMethods
    (class << base; self; end).instance_eval do
      alias_method_chain :belongs_to, :unscoped
      alias_method_chain :has_many, :unscoped
      alias_method_chain :has_one, :unscoped
    end
  end

  module ClassMethods

    def belongs_to_with_unscoped(name, options = {})
      if options.delete(:unscoped)
        add_unscoped_association(name)
      end
      belongs_to_without_unscoped(name, options)
    end

    def has_many_with_unscoped(name, options = {})
      if options.delete(:unscoped)
        add_unscoped_association(name)
      end
      has_many_without_unscoped(name, options)
    end

    def has_one_with_unscoped(name, options = {})
      if options.delete(:unscoped)
        add_unscoped_association(name)
      end
      has_one_without_unscoped(name, options)
    end

    private

    def add_unscoped_association(association_name)
      define_method(association_name) do
        self.class.reflect_on_association(association_name).klass.unscoped do
          super(association_name)
        end
      end
    end
  end
end

ActiveRecord::Base.instance_eval { include UnscopedAssociations }

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
unscoped_associations-0.3.1 lib/unscoped_associations.rb