.primary_key_prefix_type (rw)
[ GitHub ]# File 'activerecord/lib/active_record/model_schema.rb', line 163
class_attribute :primary_key_prefix_type, instance_writer: false
123456789_123456789_123456789_123456789_123456789_
Active Record objects don’t specify their attributes directly, but rather infer them from the table definition with which they’re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
See the mapping rules in table_name and the full example in README for more insight.
Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when you’re receiving the data from somewhere else, like an HTTP request. It works like this:
user = User.new(name: "David", occupation: "Code Artist")
user.name # => "David"
You can also use block initialization:
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end
And of course you can just create a bare object and specify the attributes after the fact:
user = User.new
user.name = "David"
user.occupation = "Code Artist"
Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement. The array form is to be used when the condition input is tainted and requires sanitization. The string form can be used for statements that don’t involve tainted data. The hash form works much like the array form, except only equality and range is possible. Examples:
class User < ActiveRecord::Base
def self.authenticate_unsafely(user_name, password)
where("user_name = '#{user_name}' AND password = '#{password}'").first
end
def self.authenticate_safely(user_name, password)
where("user_name = ? AND password = ?", user_name, password).first
end
def self.authenticate_safely_simply(user_name, password)
where(user_name: user_name, password: password).first
end
end
The authenticate_unsafely
method inserts the parameters directly into the query and is thus susceptible to SQL-injection attacks if the user_name
and password
parameters come directly from an HTTP request. The authenticate_safely
and authenticate_safely_simply
both will sanitize the user_name
and password
before inserting them in the query, which will ensure that an attacker can’t escape the query and fake the login (or worse).
When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That’s done by replacing the question marks with symbols and supplying a hash with values for the matching symbol keys:
Company.where(
"id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
{ id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
).first
Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND operator. For instance:
Student.where(first_name: "Harvey", status: 1)
Student.where(params[:student])
A range may be used in the hash to use the SQL BETWEEN operator:
Student.where(grade: 9..12)
An array may be used in the hash to use the SQL IN operator:
Student.where(grade: [9,11,12])
When joining tables, nested hashes or keys written in the form ‘table_name.column_name’ can be used to qualify the table name of a particular condition. For instance:
Student.joins(:schools).where(schools: { category: 'public' })
Student.joins(:schools).where('schools.category' => 'public' )
All column values are automatically available through basic accessors on the Active Record object, but sometimes you want to specialize this behavior. This can be done by overwriting the default accessors (using the same name as the attribute) and calling super
to actually change things.
class Song < ActiveRecord::Base
# Uses an integer of seconds to hold the length of the song
def length=(minutes)
super(minutes.to_i * 60)
end
def length
super / 60
end
end
In addition to the basic accessors, query methods are also automatically available on the Active Record object. Query methods allow you to test whether an attribute value is present. Additionally, when dealing with numeric values, a query method will return false if the value is zero.
For example, an Active Record User with the name
attribute has a name?
method that you can call to determine whether the user has a name:
user = User.new(name: "David")
user.name? # => true
anonymous = User.new(name: "")
anonymous.name? # => false
Query methods will also respect any overrides of default accessors:
class User
# Has admin boolean column
def admin
false
end
end
user.update(admin: true)
user.read_attribute(:admin) # => true, gets the column value
user[:admin] # => true, also gets the column value
user.admin # => false, due to the getter override
user.admin? # => false, due to the getter override
Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first. That can be done by using the <attribute>_before_type_cast
accessors that all attributes have. For example, if your Account model has a balance
attribute, you can call account.balance_before_type_cast
or account.id_before_type_cast
.
This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn’t what you want.
Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects by simple queries without turning to SQL. They work by appending the name of an attribute to find_by_
like Person.find_by_user_name
. Instead of writing Person.find_by(user_name: user_name)
, you can use Person.find_by_user_name(user_name)
.
It’s possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an RecordNotFound
error if they do not return any records, like Person.find_by_last_name!
.
It’s also possible to use multiple attributes in the same find_by_
by separating them with “and”.
Person.find_by(user_name: user_name, password: password)
Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
It’s even possible to call these dynamic finder methods on relations and named scopes.
Payment.order("created_on").find_by_amount(50)
Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method serialize. This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work.
class User < ActiveRecord::Base
serialize :preferences
end
user = User.create(preferences: { "background" => "black", "display" => large })
User.find(user.id).preferences # => { "background" => "black", "display" => large }
You can also specify a class option as the second parameter that’ll raise an exception if a serialized object is retrieved as a descendant of a class not in the hierarchy.
class User < ActiveRecord::Base
serialize :preferences, Hash
end
user = User.create(preferences: %w( one two three ))
User.find(user.id).preferences # raises SerializationTypeMismatch
When you specify a class option, the default value for that attribute will be a new instance of that class.
class User < ActiveRecord::Base
serialize :preferences, OpenStruct
end
user = User.new
user.preferences.theme_color = "red"
Active Record allows inheritance by storing the name of the class in a column that is named “type” by default. See Inheritance
for more details.
Connections are usually created through .establish_connection and retrieved by ActiveRecord::Base.lease_connection
. All classes inheriting from Base
will use this connection. But you can also set a class-specific connection. For example, if Course is an Base
, but resides in a different database, you can just say Course.establish_connection
and Course and all of its subclasses will use this connection instead.
This feature is implemented by keeping a connection pool in Base
that is a hash indexed by the class. If a connection is requested, the .retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
ActiveRecordError
- Generic error class and superclass of all other errors raised by Active Record.
AdapterNotSpecified
- The configuration hash used in .establish_connection didn’t include an :adapter
key.
AdapterNotFound
- The :adapter
key used in .establish_connection specified a non-existent adapter (or a bad spelling of an existing one).
AssociationTypeMismatch
- The object assigned to the association wasn’t of the type specified in the association definition.
AttributeAssignmentError
- An error occurred while doing a mass assignment through the #attributes=
method. You can inspect the attribute
property of the exception object to determine which attribute triggered the error.
ConnectionNotEstablished
- No connection has been established. Use .establish_connection before querying.
MultiparameterAssignmentErrors
- Collection of errors that occurred during a mass assignment using the #attributes=
method. The errors
property of this exception contains an array of AttributeAssignmentError objects that should be inspected to determine which attributes triggered the errors.
RecordInvalid
- raised by #save! and .create! when the record is invalid.
RecordNotFound
- No record responded to the .find method. Either the row with the given ID doesn’t exist or the row didn’t meet the additional restrictions. Some .find calls do not raise this exception to signal nothing was found, please check its documentation for further details.
SerializationTypeMismatch
- The serialized object wasn’t of the class specified as the second parameter.
StatementInvalid
- The database server rejected the SQL statement. The precise error is added in the message.
Note: The attributes listed are class-level attributes (accessible from both the class and instance level). So it’s possible to assign a logger to the class through .logger= which will then be used by all instances in the current object space.
Encryption::EncryptableRecord
- Included::ActiveModel::AttributeMethods
- IncludedCALL_COMPILABLE_REGEXP, NAME_COMPILABLE_REGEXP
AttributeMethods
- IncludedCallbacks
- Included::ActiveModel::SecurePassword
- IncludedNestedAttributes
- IncludedTransactions
- IncludedSecureToken
- IncludedCore
- Attributes & MethodsReturns a fully resolved DatabaseConfigurations
object.
Contains the database configuration - as is typically stored in config/database.yml - as an DatabaseConfigurations
object.
Returns the symbol representing the current setting for preventing writes.
Returns the symbol representing the current connected role.
Returns the symbol representing the current connected shard.
The job class used to destroy associations in the background.
CounterCache
- Attributes & MethodsInheritance
- Attributes & MethodsIntegration
- Attributes & MethodsModelSchema
- Attributes & MethodsNestedAttributes
- Attributes & MethodsNormalization
- Attributes & MethodsReadonlyAttributes
- Attributes & MethodsReflection
- Attributes & MethodsSignedId
- Attributes & MethodsStore
- Attributes & MethodsTimestamp
- Attributes & MethodsTokenFor
- Attributes & MethodsEncryption::EncryptableRecord
- Attributes & MethodsLocking::Optimistic
- Attributes & MethodsDelegation::DelegateCache
- ExtendedConnectionHandling
- Extendedconnected? | Returns |
connection_specification_name | Returns the connection specification name from the current class or its parent. |
connection_specification_name=, | |
shard_swapping_prohibited? | Determine whether or not shard swapping is currently prohibited. |
sharded?, primary_class? |
::ActiveModel::Callbacks
- self::ActiveModel::Naming
- selfparam_key | Returns string to use for params names. |
plural | Returns the plural class name of a record or class. |
route_key | Returns string to use while generating route names. |
singular | Returns the singular class name of a record or class. |
singular_route_key | Returns string to use while generating route names. |
uncountable? | Identifies whether the class name of a record or class is uncountable. |
extended, model_name_from_record_or_class |
Aggregations::ClassMethods
- Extendedcomposed_of | Adds reader and writer methods for manipulating a value object: |
reader_method, writer_method |
Delegation::DelegateCache
- Extendedgenerate_relation_method, inherited, initialize_relation_delegate_cache, relation_delegate_class, include_relation_methods, generated_relation_methods |
Enum
- Extended_enum_methods_module, assert_valid_enum_definition_values, assert_valid_enum_options, detect_enum_conflict!, detect_negative_enum_conditions!, enum, raise_conflict_error, _enum, inherited |
Explain
- Extendedbuild_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. |
DelegatedType
- Extendeddelegated_type | Defines this as a class that’ll delegate its type for the passed |
define_delegated_type_methods |
DynamicMatchers
- ExtendedTranslation
- Extendedi18n_scope | Set the i18n scope to override |
lookup_ancestors | Set the lookup ancestors for |
Querying
- Extended_load_from_sql, _query_by_sql, | |
async_count_by_sql | Same as |
async_find_by_sql | Same as |
count_by_sql | Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. |
find_by_sql | Executes a custom SQL query against your database and returns all the results. |
QueryCache::ClassMethods
- Extendedcache | Enable the query cache within the block if Active Record is configured. |
uncached | Disable the query cache within the block if Active Record is configured. |
ConnectionHandling
- Extendedclear_query_caches_for_current_thread | Clears the query cache for all connections associated with the current thread. |
connected_to | Connects to a role (e.g. writing, reading, or a custom role) and/or shard for the duration of the block. |
connected_to? | Returns true if role is the current connected role and/or current connected shard. |
connected_to_all_shards | Passes the block to |
connected_to_many | Connects a role and/or shard to the provided connection names. |
connecting_to | Use a specified connection. |
connection | Soft deprecated. |
connection_db_config | Returns the db_config object from the associated connection: |
connection_pool, | |
connects_to | Connects a model to the databases specified. |
establish_connection | Establishes the connection to the database. |
lease_connection | Returns the connection currently associated with the class. |
prohibit_shard_swapping | Prohibit swapping shards while inside of the passed block. |
release_connection | Return the currently leased connection into the pool. |
remove_connection, retrieve_connection, shard_keys, | |
while_preventing_writes | Prevent writing to the database regardless of role. |
with_connection | Checkouts a connection from the pool, yield it and then check it back in. |
append_to_connected_to_stack, resolve_config_for_connection, with_role_and_shard, adapter_class, clear_cache!, schema_cache |
::ActiveSupport::DescendantsTracker
- Extended::ActiveSupport::Benchmarkable
- Extendedbenchmark | Allows you to measure the execution time of a block in a template and records the result to the log. |
Serialization
- IncludedNoTouching
- Included#no_touching? | Returns |
TouchLater
- IncludedTransactions
- Included#_committed_already_called, #_trigger_destroy_callback, #_trigger_update_callback, #has_transactional_callbacks?, #_new_record_before_last_commit, #trigger_transactional_callbacks? |
AutosaveAssociation
- Included#changed_for_autosave? | Returns whether or not this record has been changed in any way (including whether any of its nested autosave associations are likewise changed). |
#destroyed_by_association | Returns the association for the parent being destroyed. |
#destroyed_by_association= | Records the association that is being destroyed and destroying this record in the process. |
#marked_for_destruction? | Returns whether or not this record will be destroyed as part of the parent’s save transaction. |
#nested_records_changed_for_autosave? | Go through nested autosave associations that are loaded in memory (without loading any new ones), and return true if any are changed for autosave. |
Timestamp
- IncludedAttributeMethods::Dirty
- self#has_changes_to_save? | Will the next call to |
#saved_changes? | Did the last call to |
::ActiveModel::Dirty
- Included#attribute_aliases, #attribute_aliases?, #attribute_method_patterns, #attribute_method_patterns?, | |
#changed? | Returns |
AttributeMethods::PrimaryKey
- self#id | Returns the primary key column’s value. |
#id= | Sets the primary key column’s value. |
#id? | Queries the primary key column’s value. |
#primary_key_values_present? |
AttributeMethods
- IncludedEncryption::EncryptableRecord
- IncludedLocking::Optimistic
- IncludedValidations
- IncludedPersistence
- Included#destroyed? | Returns true if this object has been destroyed, otherwise returns false. |
#new_record? | Returns true if this object hasn’t been saved yet – that is, a record for the object doesn’t exist in the database yet; otherwise, returns false. |
#persisted? | Returns true if the record is persisted, i.e. |
#previously_new_record? | Returns true if this object was just created – that is, prior to the last update or delete, the object didn’t exist in the database and new_record? would have returned true. |
#previously_persisted? | Returns true if this object was previously persisted but now it has been deleted. |
Core
- Included#frozen? | Returns |
#readonly? | Returns |
#strict_loading? | Returns |
#strict_loading_all? | Returns |
#strict_loading_mode, | |
#strict_loading_n_plus_one_only? | Returns |
#custom_inspect_method_defined?, #blank?, #present? |
::ActiveModel::API
- Included#_validators, #_validators?, | |
#persisted? | Indicates if the model is persisted. |
::ActiveModel::Validations
- Included#validation_context | Returns the context when running validations. |
#validation_context= |
::ActiveModel::AttributeAssignment
- IncludedMarshalling::Methods
- IncludedNormalization
- Included#normalize_attribute | Normalizes a specified attribute using its declared normalizations. |
#normalize_changed_in_place_attributes |
Suppressor
- IncludedSignedId
- Included#signed_id | Returns a signed id that’s generated using a preconfigured |
TokenFor
- Included#generate_token_for | Generates a token for a predefined |
Store
- IncludedSerialization
- Included::ActiveModel::Serializers::JSON
- Included#as_json | Returns a hash representing the model. |
#from_json | Sets the model |
::ActiveModel::Serialization
- Included#read_attribute_for_serialization | Hook method defining how an attribute value should be retrieved for serialization. |
#serializable_hash | Returns a serialized hash of your object. |
#attribute_names_for_serialization, #serializable_attributes, | |
#serializable_add_includes | Add associations specified via the |
NoTouching
- IncludedTouchLater
- Included#before_committed!, #touch, #touch_later, #init_internals, #surreptitiously_touch, #touch_deferred_attributes |
Transactions
- Included#transaction | See |
#with_transaction_returning_status | Executes a block within a transaction and captures its return value as a status flag. |
#add_to_transaction | Add the record to the current transaction so that the |
#clear_transaction_record_state | Clear the new record state and id of a record. |
#init_internals, | |
#remember_transaction_record_state | Save the new record state and id of a record so it can be restored later if a transaction fails. |
#restore_transaction_record_state | Restore the new record state and id of a record that was previously saved by a call to save_record_state. |
#transaction_include_any_action? | Determine if a transaction included an action for |
#before_committed!, | |
#committed! | Call the |
#destroy, | |
#rolledback! | Call the |
#save, #save!, #touch |
NestedAttributes
- Included#_destroy | Returns AutosaveAssociation#marked_for_destruction? It’s used in conjunction with fields_for to build a form element for the destruction of this association. |
#allow_destroy?, | |
#assign_nested_attributes_for_collection_association | Assigns the given attributes to the collection association. |
#assign_nested_attributes_for_one_to_one_association | Assigns the given attributes to the association. |
#assign_to_or_mark_for_destruction | Updates a record with the |
#call_reject_if | Determines if a record with the particular |
#check_record_limit! | Takes in a limit and checks if the attributes_collection has too many records. |
#find_record_by_id, | |
#has_destroy_flag? | Determines if a hash contains a truthy _destroy key. |
#raise_nested_attributes_record_not_found!, | |
#reject_new_record? | Determines if a new record should be rejected by checking has_destroy_flag? or if a |
#will_be_destroyed? | Only take into account the destroy flag if |
AutosaveAssociation
- Included#autosaving_belongs_to_for?, | |
#mark_for_destruction | Marks this record to be destroyed as part of the parent’s save transaction. |
#reload | Reloads the attributes of the object as usual and clears |
#validating_belongs_to_for?, #_ensure_no_duplicate_errors, | |
#_record_changed? | If the record is new or it has changed, returns true. |
#around_save_collection_association | Is used as an around_save callback to check while saving a collection association whether or not the parent was a new record before saving. |
#associated_records_to_validate_or_save | Returns the record for an association collection that should be validated or saved. |
#association_foreign_key_changed?, | |
#association_valid? | Returns whether or not the association is valid and applies any errors to the parent, |
#compute_primary_key, #init_internals, #inverse_polymorphic_association_changed?, | |
#save_belongs_to_association | Saves the associated record if it’s new or |
#save_collection_association | Saves any new associated records, or all loaded autosave associations if |
#save_has_one_association | Saves the associated record if it’s new or |
#validate_belongs_to_association | Validate the association if |
#validate_collection_association | Validate the associated records if |
#validate_has_one_association | Validate the association if |
Associations
- Included#association | Returns the association instance for the given name, instantiating it if it doesn’t already exist. |
#association_cached?, #initialize_dup, | |
#association_instance_get | Returns the specified association instance if it exists, |
#association_instance_set | Set the specified association instance. |
#init_internals |
Timestamp
- Included::ActiveModel::Validations::Callbacks
- self#run_validations! | Override run_validations! to include callbacks. |
Callbacks
- Included#after_create | Registers a callback to be called after a record is created. |
#after_destroy | Registers a callback to be called after a record is destroyed. |
#after_find | Registers a callback to be called after a record is instantiated via a finder. |
#after_initialize | Registers a callback to be called after a record is instantiated. |
#after_save | Registers a callback to be called after a record is saved. |
#after_touch | Registers a callback to be called after a record is touched. |
#after_update | Registers a callback to be called after a record is updated. |
#around_create | Registers a callback to be called around the creation of a record. |
#around_destroy | Registers a callback to be called around the destruction of a record. |
#around_save | Registers a callback to be called around the save of a record. |
#around_update | Registers a callback to be called around the update of a record. |
#before_create | Registers a callback to be called before a record is created. |
#before_destroy | Registers a callback to be called before a record is destroyed. |
#before_save | Registers a callback to be called before a record is saved. |
#before_update | Registers a callback to be called before a record is updated. |
#_create_record, #_update_record, #create_or_update, #destroy, #increment!, #touch |
AttributeMethods::Dirty
- self#*_change | This method is generated for each attribute. |
#*_changed? | This method is generated for each attribute. |
#*_previous_change | This method is generated for each attribute. |
#*_previously_changed? | This method is generated for each attribute. |
#*_previously_was | This method is generated for each attribute. |
#*_was | This method is generated for each attribute. |
#*_will_change! | This method is generated for each attribute. |
#attribute_before_last_save | Returns the original value of an attribute before the last save. |
#attribute_change_to_be_saved | Returns the change to an attribute that will be persisted during the next save. |
#attribute_in_database | Returns the value of an attribute in the database, as opposed to the in-memory value that will be persisted the next time the record is saved. |
#attributes_in_database | Returns a hash of the attributes that will change when the record is next saved. |
#changed_attribute_names_to_save | Returns an array of the names of any attributes that will change when the record is next saved. |
#changes_to_save | Returns a hash containing all the changes that will be persisted during the next save. |
#clear_*_change | This method is generated for each attribute. |
#reload |
|
#restore_*! | This method is generated for each attribute. |
#saved_change_to_attribute | Returns the change to an attribute during the last save. |
#saved_change_to_attribute? | Did this attribute change when we last saved? |
#saved_changes | Returns a hash containing all the changes that were just saved. |
#will_save_change_to_attribute? | Will this attribute change the next time we save? |
#_create_record, #_touch_row, #_update_record, #attribute_names_for_partial_inserts, #attribute_names_for_partial_updates, #init_internals |
::ActiveModel::Dirty
- Included#attribute_changed? | Dispatch target for |
#attribute_previously_changed? | Dispatch target for |
#attribute_previously_was | Dispatch target for |
#attribute_was | Dispatch target for |
#changed | Returns an array with the name of the attributes with unsaved changes. |
#changed_attributes | Returns a hash of the attributes with unsaved changes indicating their original values like |
#changes | Returns a hash of changed attributes indicating their original and new values like |
#changes_applied | Clears dirty data and moves |
#clear_attribute_changes, | |
#clear_changes_information | Clears all dirty data: current changes and previous changes. |
#previous_changes | Returns a hash of attributes that were changed before the model was saved. |
#restore_attributes | Restore all previous data of the provided attributes. |
#attribute_change | Dispatch target for |
#attribute_previous_change | Dispatch target for |
#attribute_will_change! | Dispatch target for |
#clear_attribute_change, #forget_attribute_assignments, #init_internals, #mutations_before_last_save, #mutations_from_database, | |
#restore_attribute! | Dispatch target for |
#as_json, #attribute_changed_in_place?, #init_attributes, #initialize_dup |
AttributeMethods::PrimaryKey
- self#id_before_type_cast | Returns the primary key column’s value before type cast. |
#id_in_database | Returns the primary key column’s value from the database. |
#id_was | Returns the primary key column’s previous value. |
#to_key | Returns this record’s primary key value wrapped in an array if one is available. |
#attribute_method?, #id_for_database |
AttributeMethods::Query
- self#query_attribute, | |
#attribute? | Alias for AttributeMethods::Query#query_attribute. |
#query_cast_attribute, #_query_attribute |
AttributeMethods::BeforeTypeCast
- self#attributes_before_type_cast | Returns a hash of attributes before typecasting and deserialization. |
#attributes_for_database | Returns a hash of attributes for assignment to the database. |
#read_attribute_before_type_cast | Returns the value of the attribute identified by |
#read_attribute_for_database | Returns the value of the attribute identified by |
#attribute_before_type_cast | Dispatch target for |
#attribute_came_from_user?, #attribute_for_database |
AttributeMethods::Write
- self#write_attribute | Updates the attribute identified by |
#attribute= | Alias for AttributeMethods::Write#_write_attribute. |
#_write_attribute | This method exists to avoid the expensive primary_key check internally, without breaking compatibility with the write_attribute API. |
AttributeMethods::Read
- self#read_attribute | Returns the value of the attribute identified by |
#attribute | Alias for AttributeMethods::Read#_read_attribute. |
#_read_attribute | This method exists to avoid the expensive primary_key check internally, without breaking compatibility with the read_attribute API. |
AttributeMethods
- Included#[] | Returns the value of the attribute identified by |
#[]= | Updates the attribute identified by |
#accessed_fields | Returns the name of all database fields which have been read from this model. |
#attribute_for_inspect | Returns an |
#attribute_names | Returns an array of names for the attributes available on this object. |
#attribute_present? | Returns |
#attributes | Returns a hash of all the attributes with their names as keys and the values of the attributes as values. |
#has_attribute? | Returns |
#respond_to? | A Person object with a name attribute can ask |
#attribute_method?, | |
#attributes_for_create | Filters out the virtual columns and also primary keys, from the attribute names, when the primary key is to be generated (e.g. |
#attributes_for_update | Filters the primary keys, readonly attributes and virtual columns from the attribute names. |
#attributes_with_values, #format_for_inspect, #method_missing, #pk_attribute?, #respond_to_missing?, #_has_attribute? |
::ActiveModel::AttributeMethods
- Included#attribute_missing |
|
#method_missing | Allows access to the object attributes, which are held in the hash returned by |
#respond_to?, | |
#respond_to_without_attributes? | A |
#_read_attribute, #attribute_method?, | |
#matched_attribute_method | Returns a struct representing the matching attribute method. |
#missing_attribute |
Encryption::EncryptableRecord
- Included#ciphertext_for | Returns the ciphertext for |
#decrypt | Decrypts all the encryptable attributes and saves the changes. |
#encrypt | Encrypts all the encryptable attributes and saves the changes. |
#encrypted_attribute? | Returns whether a given attribute is encrypted or not. |
#_create_record, #build_decrypt_attribute_assignments, #build_encrypt_attribute_assignments, #cant_modify_encrypted_attributes_when_frozen, #decrypt_attributes, #encrypt_attributes, #validate_encryption_allowed |
Locking::Pessimistic
- Included#lock! | Obtain a row lock on this record. |
#with_lock | Wraps the passed block in a transaction, reloading the object with a lock before yielding. |
Locking::Optimistic
- Included#_clear_locking_column, #_create_record, #_lock_value_for_database, #_query_constraints_hash, #_touch_row, #_update_row, #destroy_row, #increment!, #initialize_dup |
CounterCache
- IncludedValidations
- Included#save | The validation process on save can be skipped by passing |
#save! | Attempts to save the record just like |
#valid? | Runs all the validations within the specified context. |
#validate | Alias for Validations#valid?. |
#default_validation_context, #perform_validations, #raise_validation_error |
Integration
- Included#cache_key | Returns a stable cache key that can be used to identify this record. |
#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. |
#to_param | Returns a |
#can_use_fast_cache_version? | Detects if the value before type cast can be used to generate a cache_version. |
#raw_timestamp_to_cache_version | Converts a raw database string to |
AttributeAssignment
- Included#_assign_attributes, | |
#assign_multiparameter_attributes | Instantiates objects for all attribute classes that needs more than one constructor parameter. |
#assign_nested_parameter_attributes | Assign any deferred nested attributes after the base attributes have been set. |
#execute_callstack_for_multiparameter_attributes, #extract_callstack_for_multiparameter_attributes, #find_parameter_position, #type_cast_attribute_value |
Scoping
- IncludedInheritance
- Included#initialize_dup, | |
#ensure_proper_type | Sets the attribute used for single table inheritance to this class name if this is not the |
#initialize_internals_callback |
ModelSchema
- Included#id_value | Returns the underlying column value for a column named “id”. |
Persistence
- Included#becomes | Returns an instance of the specified |
#becomes! | Wrapper around |
#decrement | Initializes |
#decrement! | Wrapper around |
#delete | Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted). |
#destroy | Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted). |
#destroy! | Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can’t be persisted). |
#increment | Initializes |
#increment! | Wrapper around |
#reload | Reloads the record from the database. |
#save | Saves the model. |
#save! | Saves the model. |
#toggle | Assigns to |
#toggle! | Wrapper around |
#touch | Saves the record with the updated_at/on attributes set to the current time or the time specified. |
#update | Updates the attributes of the model from the passed-in hash and saves the record, all wrapped in a transaction. |
#update! | Updates its receiver just like |
#update_attribute | Updates a single attribute and saves the record. |
#update_attribute! | Updates a single attribute and saves the record. |
#update_column | Equivalent to |
#update_columns | Updates the attributes directly in the database issuing an UPDATE SQL statement and sets them in the receiver: |
#_create_record | Creates a record with values matching those of the instance attributes and returns its id. |
#_delete_row, #_find_record, #_in_memory_query_constraints_hash, #_query_constraints_hash, #_raise_readonly_record_error, #_raise_record_not_destroyed, #_raise_record_not_touched_error, #_touch_row, | |
#_update_record | Updates the associated record with values matching those of the instance attributes. |
#_update_row, #apply_scoping?, #create_or_update, | |
#destroy_associations | A hook to be overridden by association modules. |
#destroy_row, #init_internals, #strict_loaded_associations, #verify_readonly_attribute |
Core
- Included#<=> | Allows sort on objects. |
#== | Returns true if |
#all_attributes_for_inspect, #attributes_for_inspect, | |
#clone | Identical to Ruby’s clone method. |
#connection_handler, | |
#dup | Duped objects have no id assigned and are treated as new records. |
#encode_with | Populate |
#eql? | Alias for Core#==. |
#freeze | Clone and freeze the attributes hash such that associations are still accessible, even on destroyed records, but cloned models will not be frozen. |
#full_inspect | Returns all attributes of the record as a nicely formatted string, ignoring .attributes_for_inspect. |
#hash | Delegates to id in order to allow two records of the same type and id to work with something like: |
#init_with | Initialize an empty model object from |
#initialize | New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes but not yet saved (pass a hash with key names matching the associated table column names). |
#inspect | Returns the attributes of the record as a nicely formatted string. |
#inspect_with_attributes, #inspection_filter, | |
#pretty_print | Takes a PP and prettily prints this record to it, allowing you to get a nice result from |
#readonly! | Marks this record as read only. |
#slice | Returns a hash of the given methods with their names as keys and returned values as values. |
#strict_loading! | Sets the record to strict_loading mode. |
#values_at | Returns an array of the values returned by the given methods. |
#init_internals, #initialize_internals_callback, | |
#to_ary |
|
#init_attributes, | |
#init_with_attributes | Initialize an empty model object from |
#initialize_dup |
::ActiveModel::Access
- Included::ActiveModel::API
- Included#initialize | Initializes a new model with the given |
::ActiveModel::Conversion
- Included#to_key | Returns an |
#to_model | If your object is already designed to implement all of the Active Model you can use the default |
#to_param | Returns a |
#to_partial_path | Returns a |
::ActiveModel::Validations::HelperMethods
- Included#validates_absence_of | Validates that the specified attributes are blank (as defined by Object#present?). |
#validates_acceptance_of | Encapsulates the pattern of wanting to validate the acceptance of a terms of service check box (or similar agreement). |
#validates_comparison_of | Validates the value of a specified attribute fulfills all defined comparisons with another value, proc, or attribute. |
#validates_confirmation_of | Encapsulates the pattern of wanting to validate a password or email address field with a confirmation. |
#validates_exclusion_of | Validates that the value of the specified attribute is not in a particular enumerable object. |
#validates_format_of | Validates whether the value of the specified attribute is of the correct form, going by the regular expression provided. |
#validates_inclusion_of | Validates whether the value of the specified attribute is available in a particular enumerable object. |
#validates_length_of | Validates that the specified attributes match the length restrictions supplied. |
#validates_numericality_of | Validates whether the value of the specified attribute is numeric by trying to convert it to a float with |
#validates_presence_of | Validates that the specified attributes are not blank (as defined by Object#blank?). |
#validates_size_of | |
#_merge_attributes |
::ActiveModel::Validations
- Included#errors | Returns the |
#freeze, | |
#invalid? | Performs the opposite of |
#read_attribute_for_validation | Hook method defining how an attribute value should be retrieved. |
#valid? | Runs all the specified validations and returns |
#validate | Alias for ActiveModel::Validations#valid?. |
#validate! | Runs all the validations within the specified context. |
#validates_with | Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions. |
#context_for_validation, #init_internals, #raise_validation_error, #run_validations!, | |
#initialize_dup | Clean the |
::ActiveModel::AttributeAssignment
- Included#assign_attributes | Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names. |
#attribute_writer_missing | Like |
#_assign_attribute, #_assign_attributes |
::ActiveModel::ForbiddenAttributesProtection
- IncludedThis class handles dynamic methods through the method_missing method in the class ActiveRecord::AttributeMethods
# File 'activerecord/lib/active_record/readonly_attributes.rb', line 11
class_attribute :_attr_readonly, instance_accessor: false, default: []
Boolean
(rw)
# File 'activerecord/lib/active_record/readonly_attributes.rb', line 11
class_attribute :_attr_readonly, instance_accessor: false, default: []
# File 'activerecord/lib/active_record/counter_cache.rb', line 9
class_attribute :_counter_cache_columns, instance_accessor: false, default: []
Boolean
(rw)
# File 'activerecord/lib/active_record/counter_cache.rb', line 9
class_attribute :_counter_cache_columns, instance_accessor: false, default: []
# File 'activerecord/lib/active_record/core.rb', line 24
class_attribute :_destroy_association_async_job, instance_accessor: false, default: "ActiveRecord::DestroyAssociationAsyncJob"
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 24
class_attribute :_destroy_association_async_job, instance_accessor: false, default: "ActiveRecord::DestroyAssociationAsyncJob"
# File 'activerecord/lib/active_record/reflection.rb', line 11
class_attribute :_reflections, instance_writer: false, default: {}
Boolean
(rw)
# File 'activerecord/lib/active_record/reflection.rb', line 11
class_attribute :_reflections, instance_writer: false, default: {}
# File 'activerecord/lib/active_record/reflection.rb', line 12
class_attribute :aggregate_reflections, instance_writer: false, default: {}
Boolean
(rw)
# File 'activerecord/lib/active_record/reflection.rb', line 12
class_attribute :aggregate_reflections, instance_writer: false, default: {}
Boolean
(readonly)
# File 'activerecord/lib/active_record/core.rb', line 121
def self.application_record_class? # :nodoc: if ActiveRecord.application_record_class self == ActiveRecord.application_record_class else if defined?(ApplicationRecord) && self == ApplicationRecord true end end end
# File 'activerecord/lib/active_record/core.rb', line 119
class_attribute :attributes_for_inspect, instance_accessor: false, default: :all
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 119
class_attribute :attributes_for_inspect, instance_accessor: false, default: :all
# File 'activerecord/lib/active_record/reflection.rb', line 13
class_attribute :automatic_scope_inversing, instance_writer: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/reflection.rb', line 13
class_attribute :automatic_scope_inversing, instance_writer: false, default: false
# File 'activerecord/lib/active_record/reflection.rb', line 14
class_attribute :automatically_invert_plural_associations, instance_writer: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/reflection.rb', line 14
class_attribute :automatically_invert_plural_associations, instance_writer: false, default: false
# File 'activerecord/lib/active_record/core.rb', line 89
class_attribute :belongs_to_required_by_default, instance_accessor: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 89
class_attribute :belongs_to_required_by_default, instance_accessor: false
# File 'activerecord/lib/active_record/integration.rb', line 16
class_attribute :, instance_writer: false, default: :usec
Boolean
(rw)
# File 'activerecord/lib/active_record/integration.rb', line 16
class_attribute :, instance_writer: false, default: :usec
# File 'activerecord/lib/active_record/integration.rb', line 24
class_attribute :cache_versioning, instance_writer: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/integration.rb', line 24
class_attribute :cache_versioning, instance_writer: false, default: false
# File 'activerecord/lib/active_record/integration.rb', line 32
class_attribute :collection_cache_versioning, instance_writer: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/integration.rb', line 32
class_attribute :collection_cache_versioning, instance_writer: false, default: false
Returns a fully resolved DatabaseConfigurations
object.
# File 'activerecord/lib/active_record/core.rb', line 77
def self.configurations @@configurations end
Contains the database configuration - as is typically stored in config/database.yml - as an DatabaseConfigurations
object.
For example, the following database.yml…
development:
adapter: sqlite3
database: storage/development.sqlite3
production:
adapter: sqlite3
database: storage/production.sqlite3
…would result in .configurations to look like this:
#<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
#<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
@name="primary", @config={adapter: "sqlite3", database: "storage/development.sqlite3"}>,
#<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
@name="primary", @config={adapter: "sqlite3", database: "storage/production.sqlite3"}>
]>
# File 'activerecord/lib/active_record/core.rb', line 71
def self.configurations=(config) @@configurations = ActiveRecord::DatabaseConfigurations.new(config) end
# File 'activerecord/lib/active_record/core.rb', line 219
def self.connection_class # :nodoc: @connection_class ||= false end
# File 'activerecord/lib/active_record/core.rb', line 215
def self.connection_class=(b) # :nodoc: @connection_class = b end
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 223
def self.connection_class? # :nodoc: self.connection_class end
# File 'activerecord/lib/active_record/core.rb', line 133
def self.connection_handler ActiveSupport::IsolatedExecutionState[:active_record_connection_handler] || default_connection_handler end
# File 'activerecord/lib/active_record/core.rb', line 137
def self.connection_handler=(handler) ActiveSupport::IsolatedExecutionState[:active_record_connection_handler] = handler end
# File 'activerecord/lib/active_record/counter_cache.rb', line 10
class_attribute :counter_cached_association_names, instance_writer: false, default: []
Boolean
(rw)
# File 'activerecord/lib/active_record/counter_cache.rb', line 10
class_attribute :counter_cached_association_names, instance_writer: false, default: []
# File 'activerecord/lib/active_record/core.rb', line 98
class_attribute :default_connection_handler, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 98
class_attribute :default_connection_handler, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 100
class_attribute :default_role, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 100
class_attribute :default_role, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 102
class_attribute :default_shard, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 102
class_attribute :default_shard, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 47
class_attribute :destroy_association_async_batch_size, instance_writer: false, instance_predicate: false, default: nil
# File 'activerecord/lib/active_record/encryption/encryptable_record.rb', line 11
class_attribute :encrypted_attributes
Boolean
(rw)
# File 'activerecord/lib/active_record/encryption/encryptable_record.rb', line 11
class_attribute :encrypted_attributes
# File 'activerecord/lib/active_record/core.rb', line 87
class_attribute :enumerate_columns_in_select_statements, instance_accessor: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 87
class_attribute :enumerate_columns_in_select_statements, instance_accessor: false, default: false
# File 'activerecord/lib/active_record/token_for.rb', line 11
class_attribute :generated_token_verifier, instance_accessor: false, instance_predicate: false
# File 'activerecord/lib/active_record/core.rb', line 94
class_attribute :has_many_inversing, instance_accessor: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 94
class_attribute :has_many_inversing, instance_accessor: false, default: false
# File 'activerecord/lib/active_record/model_schema.rb', line 170
class_attribute :immutable_strings_by_default, instance_accessor: false
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 170
class_attribute :immutable_strings_by_default, instance_accessor: false
# File 'activerecord/lib/active_record/model_schema.rb', line 169
class_attribute :implicit_order_column, instance_accessor: false
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 169
class_attribute :implicit_order_column, instance_accessor: false
# File 'activerecord/lib/active_record/model_schema.rb', line 172
class_attribute :inheritance_column, instance_accessor: false, default: "type"
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 172
class_attribute :inheritance_column, instance_accessor: false, default: "type"
# File 'activerecord/lib/active_record/model_schema.rb', line 167
class_attribute :, instance_accessor: false, default: "ar_internal_metadata"
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 167
class_attribute :, instance_accessor: false, default: "ar_internal_metadata"
# File 'activerecord/lib/active_record/store.rb', line 101
attr_accessor :local_stored_attributes
# File 'activerecord/lib/active_record/locking/optimistic.rb', line 56
class_attribute :lock_optimistically, instance_writer: false, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/locking/optimistic.rb', line 56
class_attribute :lock_optimistically, instance_writer: false, default: true
# File 'activerecord/lib/active_record/core.rb', line 22
class_attribute :logger, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 22
class_attribute :logger, instance_writer: false
# File 'activerecord/lib/active_record/nested_attributes.rb', line 15
class_attribute :, instance_writer: false, default: {}
Boolean
(rw)
# File 'activerecord/lib/active_record/nested_attributes.rb', line 15
class_attribute :, instance_writer: false, default: {}
# File 'activerecord/lib/active_record/normalization.rb', line 8
class_attribute :normalized_attributes, default: Set.new
Boolean
(rw)
# File 'activerecord/lib/active_record/normalization.rb', line 8
class_attribute :normalized_attributes, default: Set.new
# File 'activerecord/lib/active_record/model_schema.rb', line 168
class_attribute :pluralize_table_names, instance_writer: false, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 168
class_attribute :pluralize_table_names, instance_writer: false, default: true
# File 'activerecord/lib/active_record/model_schema.rb', line 163
class_attribute :primary_key_prefix_type, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 163
class_attribute :primary_key_prefix_type, instance_writer: false
# File 'activerecord/lib/active_record/timestamp.rb', line 47
class_attribute :, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/timestamp.rb', line 47
class_attribute :, default: true
# File 'activerecord/lib/active_record/core.rb', line 96
class_attribute :run_commit_callbacks_on_first_saved_instances_in_transaction, instance_accessor: false, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 96
class_attribute :run_commit_callbacks_on_first_saved_instances_in_transaction, instance_accessor: false, default: true
# File 'activerecord/lib/active_record/model_schema.rb', line 166
class_attribute :schema_migrations_table_name, instance_accessor: false, default: "schema_migrations"
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 166
class_attribute :schema_migrations_table_name, instance_accessor: false, default: "schema_migrations"
# File 'activerecord/lib/active_record/core.rb', line 104
class_attribute :shard_selector, instance_accessor: false, default: nil
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 104
class_attribute :shard_selector, instance_accessor: false, default: nil
# File 'activerecord/lib/active_record/signed_id.rb', line 13
class_attribute :signed_id_verifier_secret, instance_writer: false
Boolean
(rw)
# File 'activerecord/lib/active_record/signed_id.rb', line 13
class_attribute :signed_id_verifier_secret, instance_writer: false
# File 'activerecord/lib/active_record/inheritance.rb', line 43
class_attribute :store_full_class_name, instance_writer: false, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/inheritance.rb', line 43
class_attribute :store_full_class_name, instance_writer: false, default: true
# File 'activerecord/lib/active_record/inheritance.rb', line 47
class_attribute :store_full_sti_class, instance_writer: false, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/inheritance.rb', line 47
class_attribute :store_full_sti_class, instance_writer: false, default: true
# File 'activerecord/lib/active_record/core.rb', line 91
class_attribute :strict_loading_by_default, instance_accessor: false, default: false
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 91
class_attribute :strict_loading_by_default, instance_accessor: false, default: false
# File 'activerecord/lib/active_record/core.rb', line 92
class_attribute :strict_loading_mode, instance_accessor: false, default: :all
Boolean
(rw)
# File 'activerecord/lib/active_record/core.rb', line 92
class_attribute :strict_loading_mode, instance_accessor: false, default: :all
# File 'activerecord/lib/active_record/model_schema.rb', line 164
class_attribute :table_name_prefix, instance_writer: false, default: ""
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 164
class_attribute :table_name_prefix, instance_writer: false, default: ""
# File 'activerecord/lib/active_record/model_schema.rb', line 165
class_attribute :table_name_suffix, instance_writer: false, default: ""
Boolean
(rw)
# File 'activerecord/lib/active_record/model_schema.rb', line 165
class_attribute :table_name_suffix, instance_writer: false, default: ""
# File 'activerecord/lib/active_record/token_for.rb', line 10
class_attribute :token_definitions, instance_accessor: false, instance_predicate: false, default: {}
# File 'activerecord/lib/active_record/core.rb', line 141
def self.asynchronous_queries_session # :nodoc: asynchronous_queries_tracker.current_session end
# File 'activerecord/lib/active_record/core.rb', line 145
def self.asynchronous_queries_tracker # :nodoc: ActiveSupport::IsolatedExecutionState[:active_record_asynchronous_queries_tracker] ||= \ AsynchronousQueriesTracker.new end
# File 'activerecord/lib/active_record/core.rb', line 205
def self.connected_to_stack # :nodoc: if connected_to_stack = ActiveSupport::IsolatedExecutionState[:active_record_connected_to_stack] connected_to_stack else connected_to_stack = Concurrent::Array.new ActiveSupport::IsolatedExecutionState[:active_record_connected_to_stack] = connected_to_stack connected_to_stack end end
# File 'activerecord/lib/active_record/core.rb', line 227
def self.connection_class_for_self # :nodoc: klass = self until klass == Base break if klass.connection_class? klass = klass.superclass end klass end
Returns the symbol representing the current setting for preventing writes.
ActiveRecord::Base.connected_to(role: :reading) do
ActiveRecord::Base.current_preventing_writes #=> true
end
ActiveRecord::Base.connected_to(role: :writing) do
ActiveRecord::Base.current_preventing_writes #=> false
end
# File 'activerecord/lib/active_record/core.rb', line 196
def self.current_preventing_writes connected_to_stack.reverse_each do |hash| return hash[:prevent_writes] if !hash[:prevent_writes].nil? && hash[:klasses].include?(Base) return hash[:prevent_writes] if !hash[:prevent_writes].nil? && hash[:klasses].include?(connection_class_for_self) end false end
Returns the symbol representing the current connected role.
ActiveRecord::Base.connected_to(role: :writing) do
ActiveRecord::Base.current_role #=> :writing
end
ActiveRecord::Base.connected_to(role: :reading) do
ActiveRecord::Base.current_role #=> :reading
end
# File 'activerecord/lib/active_record/core.rb', line 159
def self.current_role connected_to_stack.reverse_each do |hash| return hash[:role] if hash[:role] && hash[:klasses].include?(Base) return hash[:role] if hash[:role] && hash[:klasses].include?(connection_class_for_self) end default_role end
Returns the symbol representing the current connected shard.
ActiveRecord::Base.connected_to(role: :reading) do
ActiveRecord::Base.current_shard #=> :default
end
ActiveRecord::Base.connected_to(role: :writing, shard: :one) do
ActiveRecord::Base.current_shard #=> :one
end
# File 'activerecord/lib/active_record/core.rb', line 177
def self.current_shard connected_to_stack.reverse_each do |hash| return hash[:shard] if hash[:shard] && hash[:klasses].include?(Base) return hash[:shard] if hash[:shard] && hash[:klasses].include?(connection_class_for_self) end default_shard end
The job class used to destroy associations in the background.
# File 'activerecord/lib/active_record/core.rb', line 27
def self.destroy_association_async_job if _destroy_association_async_job.is_a?(String) self._destroy_association_async_job = _destroy_association_async_job.constantize end _destroy_association_async_job rescue NameError => error raise NameError, "Unable to load destroy_association_async_job: #{error.}" end
# File 'activerecord/lib/active_record/core.rb', line 242
def self.strict_loading_violation!(owner:, reflection:) # :nodoc: case ActiveRecord.action_on_strict_loading_violation when :raise = reflection. (owner) raise ActiveRecord::StrictLoadingViolationError.new( ) when :log name = "strict_loading_violation.active_record" ActiveSupport::Notifications.instrument(name, owner: owner, reflection: reflection) end end
# File 'activerecord/lib/active_record/reflection.rb', line 11
class_attribute :_reflections, instance_writer: false, default: {}
Boolean
(readonly)
# File 'activerecord/lib/active_record/reflection.rb', line 11
class_attribute :_reflections, instance_writer: false, default: {}
# File 'activerecord/lib/active_record/reflection.rb', line 12
class_attribute :aggregate_reflections, instance_writer: false, default: {}
Boolean
(readonly)
# File 'activerecord/lib/active_record/reflection.rb', line 12
class_attribute :aggregate_reflections, instance_writer: false, default: {}
# File 'activerecord/lib/active_record/reflection.rb', line 13
class_attribute :automatic_scope_inversing, instance_writer: false, default: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/reflection.rb', line 13
class_attribute :automatic_scope_inversing, instance_writer: false, default: false
# File 'activerecord/lib/active_record/reflection.rb', line 14
class_attribute :automatically_invert_plural_associations, instance_writer: false, default: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/reflection.rb', line 14
class_attribute :automatically_invert_plural_associations, instance_writer: false, default: false
# File 'activerecord/lib/active_record/integration.rb', line 16
class_attribute :, instance_writer: false, default: :usec
Boolean
(readonly)
# File 'activerecord/lib/active_record/integration.rb', line 16
class_attribute :, instance_writer: false, default: :usec
# File 'activerecord/lib/active_record/integration.rb', line 24
class_attribute :cache_versioning, instance_writer: false, default: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/integration.rb', line 24
class_attribute :cache_versioning, instance_writer: false, default: false
# File 'activerecord/lib/active_record/integration.rb', line 32
class_attribute :collection_cache_versioning, instance_writer: false, default: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/integration.rb', line 32
class_attribute :collection_cache_versioning, instance_writer: false, default: false
# File 'activerecord/lib/active_record/model_schema.rb', line 183
delegate :type_for_attribute, :column_for_attribute, to: :class
# File 'activerecord/lib/active_record/counter_cache.rb', line 10
class_attribute :counter_cached_association_names, instance_writer: false, default: []
Boolean
(readonly)
# File 'activerecord/lib/active_record/counter_cache.rb', line 10
class_attribute :counter_cached_association_names, instance_writer: false, default: []
# File 'activerecord/lib/active_record/core.rb', line 98
class_attribute :default_connection_handler, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/core.rb', line 98
class_attribute :default_connection_handler, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 100
class_attribute :default_role, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/core.rb', line 100
class_attribute :default_role, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 102
class_attribute :default_shard, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/core.rb', line 102
class_attribute :default_shard, instance_writer: false
# File 'activerecord/lib/active_record/core.rb', line 47
class_attribute :destroy_association_async_batch_size, instance_writer: false, instance_predicate: false, default: nil
# File 'activerecord/lib/active_record/core.rb', line 37
delegate :destroy_association_async_job, to: :class
# File 'activerecord/lib/active_record/encryption/encryptable_record.rb', line 11
class_attribute :encrypted_attributes
Boolean
(rw)
# File 'activerecord/lib/active_record/encryption/encryptable_record.rb', line 11
class_attribute :encrypted_attributes
# File 'activerecord/lib/active_record/locking/optimistic.rb', line 56
class_attribute :lock_optimistically, instance_writer: false, default: true
Boolean
(readonly)
# File 'activerecord/lib/active_record/locking/optimistic.rb', line 56
class_attribute :lock_optimistically, instance_writer: false, default: true
# File 'activerecord/lib/active_record/core.rb', line 22
class_attribute :logger, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/core.rb', line 22
class_attribute :logger, instance_writer: false
# File 'activerecord/lib/active_record/nested_attributes.rb', line 15
class_attribute :, instance_writer: false, default: {}
Boolean
(readonly)
# File 'activerecord/lib/active_record/nested_attributes.rb', line 15
class_attribute :, instance_writer: false, default: {}
# File 'activerecord/lib/active_record/normalization.rb', line 8
class_attribute :normalized_attributes, default: Set.new
Boolean
(rw)
# File 'activerecord/lib/active_record/normalization.rb', line 8
class_attribute :normalized_attributes, default: Set.new
# File 'activerecord/lib/active_record/model_schema.rb', line 168
class_attribute :pluralize_table_names, instance_writer: false, default: true
Boolean
(readonly)
# File 'activerecord/lib/active_record/model_schema.rb', line 168
class_attribute :pluralize_table_names, instance_writer: false, default: true
# File 'activerecord/lib/active_record/model_schema.rb', line 163
class_attribute :primary_key_prefix_type, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/model_schema.rb', line 163
class_attribute :primary_key_prefix_type, instance_writer: false
# File 'activerecord/lib/active_record/timestamp.rb', line 47
class_attribute :, default: true
Boolean
(rw)
# File 'activerecord/lib/active_record/timestamp.rb', line 47
class_attribute :, default: true
# File 'activerecord/lib/active_record/signed_id.rb', line 13
class_attribute :signed_id_verifier_secret, instance_writer: false
Boolean
(readonly)
# File 'activerecord/lib/active_record/signed_id.rb', line 13
class_attribute :signed_id_verifier_secret, instance_writer: false
# File 'activerecord/lib/active_record/inheritance.rb', line 43
class_attribute :store_full_class_name, instance_writer: false, default: true
Boolean
(readonly)
# File 'activerecord/lib/active_record/inheritance.rb', line 43
class_attribute :store_full_class_name, instance_writer: false, default: true
# File 'activerecord/lib/active_record/inheritance.rb', line 47
class_attribute :store_full_sti_class, instance_writer: false, default: true
Boolean
(readonly)
# File 'activerecord/lib/active_record/inheritance.rb', line 47
class_attribute :store_full_sti_class, instance_writer: false, default: true
# File 'activerecord/lib/active_record/model_schema.rb', line 164
class_attribute :table_name_prefix, instance_writer: false, default: ""
Boolean
(readonly)
# File 'activerecord/lib/active_record/model_schema.rb', line 164
class_attribute :table_name_prefix, instance_writer: false, default: ""
# File 'activerecord/lib/active_record/model_schema.rb', line 165
class_attribute :table_name_suffix, instance_writer: false, default: ""
Boolean
(readonly)
# File 'activerecord/lib/active_record/model_schema.rb', line 165
class_attribute :table_name_suffix, instance_writer: false, default: ""
# File 'activerecord/lib/active_record/model_schema.rb', line 183
delegate :type_for_attribute, :column_for_attribute, to: :class
# File 'activerecord/lib/active_record/core.rb', line 36
singleton_class.alias_method :destroy_association_async_job=, :_destroy_association_async_job=