123456789_123456789_123456789_123456789_123456789_

Class: ActiveRecord::AssociationRelation

Do not use. This class is for internal use only.

Constant Summary

Batches - Included

DEFAULT_ORDER, ORDER_IGNORE_MESSAGE

QueryMethods - Included

FROZEN_EMPTY_ARRAY, FROZEN_EMPTY_HASH, STRUCTURAL_VALUE_METHODS, VALID_DIRECTIONS, VALID_UNSCOPING_VALUES

FinderMethods - Included

ONE_AS_ONE

Relation - Inherited

CLAUSE_METHODS, INVALID_METHODS_FOR_DELETE_ALL, MULTI_VALUE_METHODS, SINGLE_VALUE_METHODS, VALUE_METHODS

Class Method Summary

Instance Attribute Summary

Relation - Inherited

#blank?

Returns true if relation is blank.

#eager_loading?

Returns true if relation needs eager loading.

#empty?

Returns true if there are no records.

#klass

Alias for Relation#model.

#loaded?

Alias for Relation#loaded.

#many?

Returns true if there is more than one record.

#model, #predicate_builder, #readonly?,
#scheduled?

Returns true if the relation was scheduled on the background thread pool.

#skip_preloading_value, #table, #references_eager_loaded_tables?, #empty_scope?, #has_limit_or_offset?

QueryMethods - Included

Delegation - Included

::Enumerable - Included

#many?

Returns true if the enumerable has more than 1 element.

Instance Method Summary

Relation - Inherited

#==

Compares two relations for equality.

#any?

Returns true if there are any records.

#build

Alias for Relation#new.

#cache_key

Returns a stable cache key that can be used to identify this query.

#cache_key_with_version

Returns a cache key along with the version.

#cache_version

Returns a cache version that can be used together with the cache key to form a recyclable caching scheme.

#create

Tries to create a new record with the same scoped attributes defined in the relation.

#create!

Similar to #create, but calls create! on the base class.

#create_or_find_by

Attempts to create a record with the given attributes in a table that has a unique database constraint on one or several of its columns.

#create_or_find_by!

Like #create_or_find_by, but calls create! so an exception is raised if the created record is invalid.

#delete

Deletes the row with a primary key matching the id argument, using an SQL DELETE statement, and returns the number of rows deleted.

#delete_all

Deletes the records without instantiating the records first, and hence not calling the #destroy method nor invoking callbacks.

#delete_by

Finds and deletes all records matching the specified conditions.

#destroy

Destroy an object (or multiple objects) that has the given id.

#destroy_all

Destroys the records by instantiating each record and calling its #destroy method.

#destroy_by

Finds and destroys all records matching the specified conditions.

#encode_with

Serializes the relation objects ::Array.

#explain

Runs EXPLAIN on the query or queries triggered by this relation and returns the result as a string.

#find_or_create_by

Finds the first record with the given attributes, or creates a record with the attributes if one is not found:

#find_or_create_by!

Like #find_or_create_by, but calls create! so an exception is raised if the created record is invalid.

#find_or_initialize_by

Like #find_or_create_by, but calls new instead of create.

#initialize_copy,
#insert

Inserts a single record into the database in a single SQL INSERT statement.

#insert!

Inserts a single record into the database in a single SQL INSERT statement.

#insert_all

Inserts multiple records into the database in a single SQL INSERT statement.

#insert_all!

Inserts multiple records into the database in a single SQL INSERT statement.

#inspect,
#joined_includes_values

Joins that are also marked for preloading.

#load

Causes the records to be loaded from the database if they have not been loaded already.

#load_async

Schedule the query to be performed from a background thread pool.

#loaded, #locked?,
#new

Initializes new record from relation while maintaining the current scope.

#none?

Returns true if there are no records.

#one?

Returns true if there is exactly one record.

#pretty_print,
#reload

Forces reloading of relation.

#reset, #scope_for_create,
#scoping

Scope all queries to the current scope.

#size

Returns size of the records.

#to_a

Alias for Relation#to_ary.

#to_ary

Converts relation objects to ::Array.

#to_sql

Returns sql statement for the relation.

#touch_all

Touches all records in the current relation, setting the updated_at+/+updated_on attributes to the current time or the time specified.

#update_all

Updates all records in the current relation with details given.

#update_counters

Updates the counters of the records in the current relation.

#upsert

Updates or inserts (upserts) a single record into the database in a single SQL INSERT statement.

#upsert_all

Updates or inserts (upserts) multiple records into the database in a single SQL INSERT statement.

#values, #load_records, #_create, #_create!, #_increment_attribute, #_new, #_scoping, #_substitute_values, #already_in_scope?, #current_scope_restoring_block, #exec_main_query, #exec_queries, #global_scope?, #instantiate_records, #limited_count, #skip_query_cache_if_necessary, #tables_in_string, #_exec_scope, #alias_tracker, #bind_attribute, #first_or_create, #first_or_create!, #first_or_initialize, #preload_associations, #records, #then, #update, #update!, #values_for_queries,
#where_values_hash

Returns a hash of where conditions.

#compute_cache_key, #compute_cache_version

SignedId::RelationMethods - Included

TokenFor::RelationMethods - Included

#find_by_token_for

Finds a record using a given token for a predefined purpose.

#find_by_token_for!

Finds a record using a given token for a predefined purpose.

FinderMethods - Included

#exists?

Returns true if a record exists in the table that matches the id or conditions given, or false otherwise.

#fifth

Find the fifth record.

#fifth!

Same as #fifth but raises RecordNotFound if no record is found.

#find

Find by id - This can either be a specific id (ID), a list of ids (ID, ID, ID), or an array of ids ([ID, ID, ID]).

#find_by

Finds the first record matching the specified conditions.

#find_by!

Like #find_by, except that if no record is found, raises an RecordNotFound error.

#find_sole_by

Finds the sole matching record.

#first

Find the first record (or first N records if a parameter is supplied).

#first!

Same as #first but raises RecordNotFound if no record is found.

#forty_two

Find the forty-second record.

#forty_two!

Same as #forty_two but raises RecordNotFound if no record is found.

#fourth

Find the fourth record.

#fourth!

Same as #fourth but raises RecordNotFound if no record is found.

#include?

Returns true if the relation contains the given record or false otherwise.

#last

Find the last record (or last N records if a parameter is supplied).

#last!

Same as #last but raises RecordNotFound if no record is found.

#member?
#second

Find the second record.

#second!

Same as #second but raises RecordNotFound if no record is found.

#second_to_last

Find the second-to-last record.

#second_to_last!

Same as #second_to_last but raises RecordNotFound if no record is found.

#sole

Finds the sole matching record.

#take

Gives a record (or N records if a parameter is supplied) without any implied order.

#take!

Same as #take but raises RecordNotFound if no record is found.

#third

Find the third record.

#third!

Same as #third but raises RecordNotFound if no record is found.

#third_to_last

Find the third-to-last record.

#third_to_last!

Same as #third_to_last but raises RecordNotFound if no record is found.

#_order_columns, #apply_join_dependency, #construct_relation_for_exists, #find_last, #find_nth, #find_nth_from_last, #find_nth_with_limit, #find_one, #find_some, #find_some_ordered, #find_take, #find_take_with_limit, #find_with_ids, #ordered_relation, #using_limitable_reflections?,
#raise_record_not_found_exception!

This method is called whenever no records are found with either a single id or multiple ids and raises an RecordNotFound exception.

Calculations - Included

#async_average

Same as #average, but performs the query asynchronously and returns an Promise.

#async_count

Same as #count, but performs the query asynchronously and returns an Promise.

#async_ids

Same as #ids, but performs the query asynchronously and returns an Promise.

#async_maximum

Same as #maximum, but performs the query asynchronously and returns an Promise.

#async_minimum

Same as #minimum, but performs the query asynchronously and returns an Promise.

#async_pick

Same as #pick, but performs the query asynchronously and returns an Promise.

#async_pluck

Same as #pluck, but performs the query asynchronously and returns an Promise.

#async_sum

Same as #sum, but performs the query asynchronously and returns an Promise.

#average

Calculates the average value on a given column.

#calculate

This calculates aggregate values in the given column.

#count

Count the records.

#ids

Returns the base model’s ID’s for the relation using the table’s primary key.

#maximum

Calculates the maximum value on a given column.

#minimum

Calculates the minimum value on a given column.

#pick

Pick the value(s) from the named column(s) in the current relation.

#pluck

Use #pluck as a shortcut to select one or more attributes without loading an entire record object per row.

#sum

Calculates the sum of values on a given column.

#aggregate_column, #all_attributes?, #build_count_subquery, #build_count_subquery?, #distinct_select?, #has_include?, #lookup_cast_type_from_join_dependencies, #operation_over_aggregate_column, #perform_calculation, #select_for_count, #type_cast_calculated_value, #type_cast_pluck_values, #type_for, #execute_grouped_calculation, #execute_simple_calculation

SpawnMethods - Included

#except

Removes from the query the condition(s) specified in skips.

#merge

Merges in the conditions from other, if other is an Relation.

#only

Removes any condition from the query other than the one(s) specified in onlies.

#relation_with, #merge!, #spawn

QueryMethods - Included

#and

Returns a new relation, which is the logical intersection of this relation and the one passed as an argument.

#annotate

Adds an SQL comment to queries generated from this relation.

#create_with

Sets attributes to be used when creating new records from a relation object.

#distinct

Specifies whether the records should be unique or not.

#eager_load

Specify associations args to be eager loaded using a LEFT OUTER JOIN.

#excluding

Excludes the specified record (or collection of records) from the resulting relation.

#extending

Used to extend a scope with additional methods, either through a module or through a block provided.

#extensions,
#extract_associated

Extracts a named association from the relation.

#from

Specifies the table from which the records will be fetched.

#group

Allows to specify a group attribute:

#having

Allows to specify a HAVING clause.

#in_order_of

Applies an ORDER BY clause based on a given column, ordered and filtered by a specific set of values.

#includes

Specify associations args to be eager loaded to prevent N + 1 queries.

#invert_where

Allows you to invert an entire where clause instead of manually applying conditions.

#joins

Performs JOINs on args.

#left_joins
#left_outer_joins

Performs LEFT OUTER JOINs on args:

#limit

Specifies a limit for the number of records to retrieve.

#lock

Specifies locking settings (default to true).

#none

Returns a chainable relation with zero records.

#offset

Specifies the number of rows to skip before returning rows.

#optimizer_hints

Specify optimizer hints to be used in the SELECT statement.

#or

Returns a new relation, which is the logical union of this relation and the one passed as an argument.

#order

Applies an ORDER BY clause to a query.

#preload

Specify associations args to be eager loaded using separate queries.

#readonly

Mark a relation as readonly.

#references

Use to indicate that the given table_names are referenced by an SQL string, and should therefore be JOINed in any query rather than loaded separately.

#regroup

Allows you to change a previously set group statement.

#reorder

Replaces any existing order defined on the relation with the specified order.

#reselect

Allows you to change a previously set select statement.

#reverse_order

Reverse the existing order clause on the relation.

#rewhere

Allows you to change a previously set where condition for a given attribute, instead of appending to that condition.

#select

Works in two unique ways.

#strict_loading

Sets the returned relation to strict_loading mode.

#structurally_compatible?

Checks whether the given relation is structurally compatible with this relation, to determine if it’s possible to use the #and and #or methods without raising an error.

#uniq!

Deduplicate multiple values.

#unscope

Removes an unwanted relation that is already defined on a chain of relations.

#where

Returns a new relation, which is the result of filtering the current relation according to the conditions in the arguments.

#with

Add a Common Table Expression (CTE) that you can then reference within another SELECT statement.

#with_recursive

Add a recursive Common Table Expression (CTE) that you can then reference within another SELECT statement.

#without
#arel_columns, #async!,
#build_having_clause
#arel_column, #arel_column_aliases_from_hash, #arel_column_with_table, #arel_columns_from_hash, #assert_modifiable!, #async, #build_arel, #build_bound_sql_literal, #build_case_for_value_position, #build_cast_value, #build_from, #build_join_buckets, #build_join_dependencies, #build_joins, #build_named_bound_sql_literal, #build_order, #build_select, #build_with, #build_with_expression_from_value, #build_with_join_node, #build_with_value_from_hash,
#check_if_method_has_arguments!

Checks to make sure that the arguments are not blank.

#column_references, #does_not_support_reverse?, #each_join_dependencies, #extract_table_name_from, #flattened_args, #lookup_table_klass_from_join_dependencies, #order_column, #preprocess_order_args, #process_select_args, #process_with_args, #resolve_arel_attributes, #reverse_sql_order, #sanitize_order_arguments, #select_association_list, #select_named_joins, #table_name_matches?, #validate_order_args, #_select!, #all, #and!,
#annotate!

Like #annotate, but modifies relation in place.

#arel

Returns the ::Arel object associated with the relation.

#construct_join_dependency, #create_with!,
#distinct!

Like #distinct, but modifies relation in place.

#eager_load!, #excluding!, #extending!, #from!, #group!, #having!, #includes!, #invert_where!, #joins!, #left_outer_joins!, #limit!, #lock!, #none!, #offset!, #optimizer_hints!, #or!,
#order!

Same as #order but operates on relation in-place instead of copying.

#preload!, #readonly!, #references!,
#regroup!

Same as #regroup but operates on relation in-place instead of copying.

#reorder!

Same as #reorder but operates on relation in-place instead of copying.

#reselect!

Same as #reselect but operates on relation in-place instead of copying.

#reverse_order!, #skip_preloading!, #skip_query_cache!, #strict_loading!, #unscope!, #where!,
#with!

Like #with, but modifies relation in place.

#with_recursive!

Like #with_recursive but modifies the relation in place.

#build_subquery, #build_where_clause, #structurally_incompatible_values_for

::ActiveModel::ForbiddenAttributesProtection - Included

Batches - Included

#find_each

Looping through a collection of records from the database (using the Scoping::Named::ClassMethods#all method, for example) is very inefficient since it will try to instantiate all the objects at once.

#find_in_batches

Yields each batch of records that was found by the find options as an array.

#in_batches

Yields Relation objects to work with a batch of records.

#act_on_ignored_order, #apply_finish_limit, #apply_limits, #apply_start_limit, #batch_condition, #batch_on_loaded_relation, #batch_on_unloaded_relation, #build_batch_orders,
#compare_values_for_order

This is a custom implementation of <=> operator, which also takes into account how the collection will be ordered.

#ensure_valid_options_for_batching!, #record_cursor_values

Explain - Included

#build_explain_clause, #render_bind,
#collecting_queries_for_explain

Executes the block with the collect flag enabled.

#exec_explain

Makes the adapter execute EXPLAIN for the tuples of queries and bindings.

Delegation - Included

::Enumerable - Included

#compact_blank

Returns a new ::Array without the blank items.

#exclude?

The negative of the Enumerable#include?.

#excluding

Returns a copy of the enumerable excluding the specified elements.

#in_order_of

Returns a new ::Array where the order has been set to that provided in the series, based on the key of the objects in the original enumerable.

#including

Returns a new array that includes the passed elements.

#index_by

Convert an enumerable to a hash, using the block result as the key and the element as the value.

#index_with

Convert an enumerable to a hash, using the element as the key and the block result as the value.

#maximum

Calculates the maximum from the extracted elements.

#minimum

Calculates the minimum from the extracted elements.

#pick

Extract the given key from the first element in the enumerable.

#pluck

Extract the given key from each element in the enumerable.

#sole

Returns the sole item in the enumerable.

#without
#as_json

::ActiveSupport::EnumerableCoreExt::Constants - Included

Constructor Details

.new(klass, association) ⇒ AssociationRelation

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 5

def initialize(klass, association, **)
  super(klass)
  @association = association
end

Instance Method Details

#==(other)

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 14

def ==(other)
  other == records
end

#_create(attributes, &block) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 35

def _create(attributes, &block)
  @association.create(attributes, &block)
end

#_create!(attributes, &block) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 39

def _create!(attributes, &block)
  @association.create!(attributes, &block)
end

#_new(attributes, &block) (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 31

def _new(attributes, &block)
  @association.build(attributes, &block)
end

#exec_queries (private)

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 43

def exec_queries
  super do |record|
    @association.set_inverse_instance_from_queries(record)
    @association.set_strict_loading(record)
    yield record if block_given?
  end
end

#proxy_association

[ GitHub ]

  
# File 'activerecord/lib/active_record/association_relation.rb', line 10

def proxy_association
  @association
end