Module: ActiveRecord::Sanitization::ClassMethods

### Home Classes Methods

### In Files

- lib/active_record/sanitization.rb

### Methods

- #expand_hash_conditions_for_aggregates
- #sanitize_conditions
- #sanitize_sql
- #sanitize_sql_array
- #sanitize_sql_for_assignment
- #sanitize_sql_for_conditions
- #sanitize_sql_hash
- #sanitize_sql_hash_for_assignment
- #sanitize_sql_hash_for_conditions

### 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::Sanitization::ClassMethods

### Protected Instance Methods

expand_hash_conditions_for_aggregates(attrs) click to toggle source

Accepts a hash of SQL conditions and replaces those attributes that correspond to a `composed_of` relationship with their expanded aggregate attribute values. Given:

    class Person < ActiveRecord::Base
      composed_of :address, :class_name => "Address",
        :mapping => [%w(address_street street), %w(address_city city)]
    end

Then:

    { :address => Address.new("813 abc st.", "chicago") }
      # => { :address_street => "813 abc st.", :address_city => "chicago" }

    # File lib/active_record/sanitization.rb, line 57
    def expand_hash_conditions_for_aggregates(attrs)
      expanded_attrs = {}
      attrs.each do |attr, value|
        unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil?
          mapping = aggregate_mapping(aggregation)
          mapping.each do |field_attr, aggregate_attr|
            if mapping.size == 1 && !value.respond_to?(aggregate_attr)
              expanded_attrs[field_attr] = value
            else
              expanded_attrs[field_attr] = value.send(aggregate_attr)
            end
          end
        else
          expanded_attrs[attr] = value
        end
      end
      expanded_attrs
    end

sanitize_conditions(condition, table_name = self.table_name) click to toggle source
Alias for: sanitize_sql
sanitize_sql(condition, table_name = self.table_name) click to toggle source
Also aliased as: sanitize_conditions
Alias for: sanitize_sql_for_conditions
sanitize_sql_array(ary) click to toggle source

Accepts an array of conditions. The array has each value sanitized and interpolated into the SQL statement.

    ["name='%s' and group_id='%s'", "foo'bar", 4]  returns  "name='foo''bar' and group_id='4'"

    # File lib/active_record/sanitization.rb, line 112
    def sanitize_sql_array(ary)
      statement, *values = ary
      if values.first.is_a?(Hash) && statement =~ /:\w+/
        replace_named_bind_variables(statement, values.first)
      elsif statement.include?('?')
        replace_bind_variables(statement, values)
      elsif statement.blank?
        statement
      else
        statement % values.collect { |value| connection.quote_string(value.to_s) }
      end
    end

sanitize_sql_for_assignment(assignments) click to toggle source

Accepts an array, hash, or string of SQL conditions and sanitizes them into a valid SQL fragment for a SET clause.

    { :name => nil, :group_id => 4 }  returns "name = NULL , group_id='4'"

    # File lib/active_record/sanitization.rb, line 38
    def sanitize_sql_for_assignment(assignments)
      case assignments
        when Array; sanitize_sql_array(assignments)
        when Hash;  sanitize_sql_hash_for_assignment(assignments)
        else        assignments
      end
    end

sanitize_sql_for_conditions(condition, table_name = self.table_name) click to toggle source

Accepts an array, hash, or string of SQL conditions and sanitizes them into a valid SQL fragment for a WHERE clause.

    ["name='%s' and group_id='%s'", "foo'bar", 4]  returns  "name='foo''bar' and group_id='4'"
    { :name => "foo'bar", :group_id => 4 }  returns "name='foo''bar' and group_id='4'"
    "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"

    # File lib/active_record/sanitization.rb, line 24
    def sanitize_sql_for_conditions(condition, table_name = self.table_name)
      return nil if condition.blank?

      case condition
      when Array; sanitize_sql_array(condition)
      when Hash;  sanitize_sql_hash_for_conditions(condition, table_name)
      else        condition
      end
    end

Also aliased as: sanitize_sql
sanitize_sql_hash(attrs, default_table_name = self.table_name) click to toggle source
Alias for: sanitize_sql_hash_for_conditions
sanitize_sql_hash_for_assignment(attrs) click to toggle source

Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.

    { :status => nil, :group_id => 1 }
      # => "status = NULL , group_id = 1"

    # File lib/active_record/sanitization.rb, line 103
    def sanitize_sql_hash_for_assignment(attrs)
      attrs.map do |attr, value|
        "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
      end.join(', ')
    end

sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) click to toggle source

Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.

    { :name => "foo'bar", :group_id => 4 }
      # => "name='foo''bar' and group_id= 4"
    { :status => nil, :group_id => [1,2,3] }
      # => "status IS NULL and group_id IN (1,2,3)"
    { :age => 13..18 }
      # => "age BETWEEN 13 AND 18"
    { 'other_records.id' => 7 }
      # => "`other_records`.`id` = 7"
    { :other_records => { :id => 7 } }
      # => "`other_records`.`id` = 7"

And for value objects on a composed_of relationship:

    { :address => Address.new("123 abc st.", "chicago") }
      # => "address_street='123 abc st.' and address_city='chicago'"

    # File lib/active_record/sanitization.rb, line 90
    def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
      attrs = expand_hash_conditions_for_aggregates(attrs)

      table = Arel::Table.new(table_name).alias(default_table_name)
      PredicateBuilder.build_from_hash(arel_engine, attrs, table).map { |b|
        connection.visitor.accept b
      }.join(' AND ')
    end

Also aliased as: sanitize_sql_hash

[Validate]

Generated with the Darkfish Rdoc Generator 2.