Module: ActiveRecord::Scoping::ClassMethods

### Home Classes Methods

### In Files

- lib/active_record/scoping.rb

### Methods

- #with_exclusive_scope
- #with_scope

### Files

- README.rdoc

### Class/Module Index

Quicksearch

- ActiveRecord
- ActiveRecord::ActiveRecordError
- ActiveRecord::AdapterNotFound
- ActiveRecord::AdapterNotSpecified
- ActiveRecord::Aggregations
- ActiveRecord::Aggregations::ClassMethods
- ActiveRecord::AssociationTypeMismatch
- ActiveRecord::Associations
- ActiveRecord::Associations::ClassMethods
- ActiveRecord::AttributeAssignment
- ActiveRecord::AttributeAssignment::ClassMethods
- ActiveRecord::AttributeAssignmentError
- ActiveRecord::AttributeMethods
- ActiveRecord::AttributeMethods::BeforeTypeCast
- ActiveRecord::AttributeMethods::ClassMethods
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead
- ActiveRecord::AttributeMethods::DeprecatedUnderscoreRead::ClassMethods
- ActiveRecord::AttributeMethods::Dirty
- ActiveRecord::AttributeMethods::PrimaryKey
- ActiveRecord::AttributeMethods::PrimaryKey::ClassMethods
- ActiveRecord::AttributeMethods::Query
- ActiveRecord::AttributeMethods::Read
- ActiveRecord::AttributeMethods::Read::ClassMethods
- ActiveRecord::AttributeMethods::Serialization
- ActiveRecord::AttributeMethods::Serialization::Attribute
- ActiveRecord::AttributeMethods::Serialization::ClassMethods
- ActiveRecord::AttributeMethods::TimeZoneConversion
- ActiveRecord::AttributeMethods::TimeZoneConversion::ClassMethods
- ActiveRecord::AttributeMethods::Write
- ActiveRecord::AttributeMethods::Write::ClassMethods
- ActiveRecord::AutosaveAssociation
- ActiveRecord::AutosaveAssociation::ClassMethods
- ActiveRecord::Base
- ActiveRecord::Batches
- ActiveRecord::Calculations
- ActiveRecord::Callbacks
- ActiveRecord::Coders
- ActiveRecord::ConfigurationError
- ActiveRecord::ConnectionAdapters
- ActiveRecord::ConnectionAdapters::AbstractAdapter
- ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter
- ActiveRecord::ConnectionAdapters::ConnectionHandler
- ActiveRecord::ConnectionAdapters::ConnectionManagement
- ActiveRecord::ConnectionAdapters::ConnectionPool
- ActiveRecord::ConnectionAdapters::DatabaseLimits
- ActiveRecord::ConnectionAdapters::DatabaseStatements
- ActiveRecord::ConnectionAdapters::Mysql2Adapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter
- ActiveRecord::ConnectionAdapters::MysqlAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::TableDefinition
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::Utils
- ActiveRecord::ConnectionAdapters::PostgreSQLColumn
- ActiveRecord::ConnectionAdapters::QueryCache
- ActiveRecord::ConnectionAdapters::Quoting
- ActiveRecord::ConnectionAdapters::SQLiteAdapter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::ExplainPrettyPrinter
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::StatementPool
- ActiveRecord::ConnectionAdapters::SQLiteAdapter::Version
- ActiveRecord::ConnectionAdapters::SchemaCache
- ActiveRecord::ConnectionAdapters::SchemaStatements
- ActiveRecord::ConnectionAdapters::StatementPool
- ActiveRecord::ConnectionAdapters::Table
- ActiveRecord::ConnectionAdapters::TableDefinition
- ActiveRecord::ConnectionNotEstablished
- ActiveRecord::ConnectionTimeoutError
- ActiveRecord::CounterCache
- ActiveRecord::DangerousAttributeError
- ActiveRecord::Delegation
- ActiveRecord::DynamicFinderMatch
- ActiveRecord::DynamicMatchers
- ActiveRecord::DynamicScopeMatch
- ActiveRecord::Explain
- ActiveRecord::FinderMethods
- ActiveRecord::Fixtures
- ActiveRecord::Fixtures::File
- ActiveRecord::Generators
- ActiveRecord::Generators::Migration
- ActiveRecord::Generators::MigrationGenerator
- ActiveRecord::Generators::ModelGenerator
- ActiveRecord::Generators::ObserverGenerator
- ActiveRecord::Generators::SessionMigrationGenerator
- ActiveRecord::IdentityMap
- ActiveRecord::IdentityMap::Middleware
- ActiveRecord::Inheritance
- ActiveRecord::Inheritance::ClassMethods
- ActiveRecord::Integration
- ActiveRecord::InvalidForeignKey
- ActiveRecord::IrreversibleMigration
- ActiveRecord::Locking
- ActiveRecord::Locking::Optimistic
- ActiveRecord::Locking::Optimistic::ClassMethods
- ActiveRecord::Locking::Pessimistic
- ActiveRecord::LogSubscriber
- ActiveRecord::Migration
- ActiveRecord::Migration::CommandRecorder
- ActiveRecord::MigrationProxy
- ActiveRecord::ModelSchema
- ActiveRecord::ModelSchema::ClassMethods
- ActiveRecord::MultiparameterAssignmentErrors
- ActiveRecord::NestedAttributes
- ActiveRecord::NestedAttributes::ClassMethods
- ActiveRecord::NestedAttributes::TooManyRecords
- ActiveRecord::Observer
- ActiveRecord::Persistence
- ActiveRecord::Persistence::ClassMethods
- ActiveRecord::PreparedStatementInvalid
- ActiveRecord::QueryCache
- ActiveRecord::QueryCache::ClassMethods
- ActiveRecord::QueryMethods
- ActiveRecord::Querying
- ActiveRecord::Railtie
- ActiveRecord::Railties
- ActiveRecord::Railties::ControllerRuntime
- ActiveRecord::Railties::ControllerRuntime::ClassMethods
- ActiveRecord::ReadOnlyRecord
- ActiveRecord::ReadonlyAttributes
- ActiveRecord::ReadonlyAttributes::ClassMethods
- ActiveRecord::RecordInvalid
- ActiveRecord::RecordNotFound
- ActiveRecord::RecordNotSaved
- ActiveRecord::RecordNotUnique
- ActiveRecord::Reflection
- ActiveRecord::Reflection::ClassMethods
- ActiveRecord::Reflection::MacroReflection
- ActiveRecord::Result
- ActiveRecord::Rollback
- ActiveRecord::Sanitization
- ActiveRecord::Sanitization::ClassMethods
- ActiveRecord::Schema
- ActiveRecord::Scoping
- ActiveRecord::Scoping::ClassMethods
- ActiveRecord::Scoping::Default
- ActiveRecord::Scoping::Default::ClassMethods
- ActiveRecord::Scoping::Named
- ActiveRecord::Scoping::Named::ClassMethods
- ActiveRecord::Serialization
- ActiveRecord::SerializationTypeMismatch
- ActiveRecord::SessionStore
- ActiveRecord::SessionStore::Session
- ActiveRecord::SessionStore::SqlBypass
- ActiveRecord::SpawnMethods
- ActiveRecord::StaleObjectError
- ActiveRecord::StatementInvalid
- ActiveRecord::Store
- ActiveRecord::Store::ClassMethods
- ActiveRecord::TestFixtures
- ActiveRecord::TestFixtures::ClassMethods
- ActiveRecord::ThrowResult
- ActiveRecord::Timestamp
- ActiveRecord::Transactions
- ActiveRecord::Transactions::ClassMethods
- ActiveRecord::Translation
- ActiveRecord::UnknownAttributeError
- ActiveRecord::UnknownPrimaryKey
- ActiveRecord::Validations
- ActiveRecord::Validations::AssociatedValidator
- ActiveRecord::Validations::ClassMethods
- ActiveRecord::Validations::UniquenessValidator
- ActiveRecord::WrappedDatabaseException
- Mysql
- Mysql::Result
- Mysql::Stmt
- Mysql::Time
- ArJdbcMySQL
- ArJdbcMySQL::Error

No matching classes.

# ActiveRecord::Scoping::ClassMethods

### Public Instance Methods

with_scope(scope = {}, action = :merge, &block) click to toggle source

with_scope lets you apply options to inner block incrementally. It takes a hash and the keys must be `:find` or `:create`. `:find` parameter is `Relation` while `:create` parameters are an attributes hash.

    class Article < ActiveRecord::Base
      def self.create_with_scope
        with_scope(:find => where(:blog_id => 1), :create => { :blog_id => 1 }) do
          find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
          a = create(1)
          a.blog_id # => 1
        end
      end
    end

In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of `where`, `includes`, and `joins` operations in `Relation`, which are merged.

`joins` operations are uniqued so multiple scopes can join in the same table without table aliasing problems. If you need to join multiple tables, but still want one of the tables to be uniqued, use the array of strings format for your joins.

    class Article < ActiveRecord::Base
      def self.find_with_scope
        with_scope(:find => where(:blog_id => 1).limit(1), :create => { :blog_id => 1 }) do
          with_scope(:find => limit(10)) do
            all # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
          end
          with_scope(:find => where(:author_id => 3)) do
            all # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
          end
        end
      end
    end

You can ignore any previous scopings by using the `with_exclusive_scope` method.

    class Article < ActiveRecord::Base
      def self.find_with_exclusive_scope
        with_scope(:find => where(:blog_id => 1).limit(1)) do
          with_exclusive_scope(:find => limit(10)) do
            all # => SELECT * from articles LIMIT 10
          end
        end
      end
    end

Note: the `:find` scope also has effect on update and deletion methods, like `update_all` and `delete_all`.

    # File lib/active_record/scoping.rb, line 60
    def with_scope(scope = {}, action = :merge, &block)
      # If another Active Record class has been passed in, get its current scope
      scope = scope.current_scope if !scope.is_a?(Relation) && scope.respond_to?(:current_scope)

      previous_scope = self.current_scope

      if scope.is_a?(Hash)
        # Dup first and second level of hash (method and params).
        scope = scope.dup
        scope.each do |method, params|
          scope[method] = params.dup unless params == true
        end

        scope.assert_valid_keys([ :find, :create ])
        relation = construct_finder_arel(scope[:find] || {})
        relation.default_scoped = true unless action == :overwrite

        if previous_scope && previous_scope.create_with_value && scope[:create]
          scope_for_create = if action == :merge
            previous_scope.create_with_value.merge(scope[:create])
          else
            scope[:create]
          end

          relation = relation.create_with(scope_for_create)
        else
          scope_for_create = scope[:create]
          scope_for_create ||= previous_scope.create_with_value if previous_scope
          relation = relation.create_with(scope_for_create) if scope_for_create
        end

        scope = relation
      end

      scope = previous_scope.merge(scope) if previous_scope && action == :merge

      self.current_scope = scope
      begin
        yield
      ensure
        self.current_scope = previous_scope
      end
    end

### Protected Instance Methods

with_exclusive_scope(method_scoping = {}, &block) click to toggle source

Works like with_scope, but discards any nested properties.

    # File lib/active_record/scoping.rb, line 107
    def with_exclusive_scope(method_scoping = {}, &block)
      if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) }
        raise ArgumentError,   New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope:  User.unscoped.where(:active => true)  Or call unscoped with a block:  User.unscoped do  User.where(:active => true).all  end
      end
      with_scope(method_scoping, :overwrite, &block)
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.