The Rails Guides: Active Record Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

What is Active Record?

A

Active Record is the M in MVC - the model - which represents the layer of the system responsible for managing business data and logic. It facilitates the creation and usage of business objects that require persistent storage to a database. Active Record is an implementation of the Active Record pattern, which describes an Object-Relational Mapping (ORM) system.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the Active Record Pattern?

A

The Active Record pattern involves objects carrying both persistent data and behavior that operates on that data. It advocates for including data access logic as part of the object, educating users on how to interact with the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Object-Relational Mapping (ORM)?

A

Object-Relational Mapping (ORM) connects the objects of an application to tables in a relational database management system. It allows properties and relationships of objects to be stored and retrieved from a database without directly writing SQL statements, reducing overall database access code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is Convention over Configuration in Active Record?

A

Convention over Configuration is a principle where Rails assumes default configurations for applications, reducing the need for explicit configuration. In Active Record, following Rails conventions requires minimal configuration, simplifying the development process. Explicit configuration is only necessary in cases where the standard convention cannot be followed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are some mechanisms provided by Active Record as an ORM framework?

A

A: Active Record offers several mechanisms, including:Representing models and their data.
Managing associations between models.
Handling inheritance hierarchies through related models.
Validating models before persisting to the database.
Performing database operations in an object-oriented manner.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does Active Record handle naming conventions for models and database tables?

A

Active Record uses naming conventions to establish mappings between models and database tables. By default, class names are pluralized to find the corresponding table names, following Ruby conventions (CamelCase for class names, snake_case for table names). For example, a class named “BookClub” corresponds to a table named “book_clubs”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are some schema conventions used by Active Record for database columns?

A

A: Active Record uses naming conventions for database columns based on their purpose:

Foreign keys follow the pattern: singularized_table_name_id.

Primary keys are typically named “id” and are automatically created by Active Record (bigint for PostgreSQL and MySQL, integer for SQLite).

Optional column names like “created_at”, “updated_at”, “lock_version”, and “type” offer additional functionality when present.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can you create Active Record models in Rails?

A

To create Active Record models, you subclass the ApplicationRecord class provided by Rails. For example:

This creates a Product model mapped to a “products” table in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can you override naming conventions in Active Record?

A

You can override naming conventions by manually setting table names or primary keys using methods like self.table_name= and self.primary_key= in your model classes. Additionally, you can customize table names using options in Active Record Migrations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are some CRUD operations provided by Active Record?

A

Active Record provides CRUD operations to Create, Read, Update, and Delete data. Methods like create, all, find_by, update, and destroy facilitate these operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How does Active Record perform validations?

A

Active Record allows you to validate the state of a model before it gets written into the database. It offers methods like validates to check attributes for conditions such as presence, uniqueness, and format. Validation methods like save, create, and update return false if validation fails, preventing database operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are callbacks in Active Record?

A

Active Record callbacks enable you to attach code to certain events in the life cycle of your models, such as creating, updating, or destroying records. Methods like after_create, before_update, and after_destroy execute custom code when these events occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are migrations in Rails?

A

Migrations in Rails are a convenient way to manage changes to a database schema. Written in a domain-specific language, migrations are stored in files and executed against any database supported by Active Record. Migrations provide a version-controlled way to create, modify, and delete database tables and columns.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How do associations work in Active Record?

A

Active Record associations allow you to define relationships between models, such as one-to-one, one-to-many, and many-to-many relationships. Associations are established using methods like has_many, belongs_to, and has_and_belongs_to_many, enabling convenient management of related data in the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is an overview of migrations in database schema evolution?

A

Migrations provide a structured way to modify your database schema over time, using a Ruby DSL instead of manual SQL writing. Each migration represents a version of the database, progressing from an initial empty state to the latest version with tables, columns, or entries added or removed. Active Record handles schema updates, and the db/schema.rb file is updated accordingly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How does Active Record manage database schema evolution over time?

A

Active Record tracks database schema changes using migrations, which are Ruby DSL scripts that describe alterations to the schema. It handles updating the schema from its current state to the latest version specified by the migrations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the purpose of the db/schema.rb file in the context of database migrations?

A

The db/schema.rb file serves as a representation of the current database schema. Active Record updates this file to reflect the latest structure of the database after each migration, ensuring synchronization between the schema and the database itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the role of transactions in database migrations, and how do they affect migration rollbacks?

A

Transactions ensure that migrations are executed atomically, either completing all changes successfully or rolling back if an error occurs. In databases supporting transactional DDL statements, each migration is wrapped in a transaction, allowing for seamless rollback on failure. However, in databases without DDL transaction support, partial changes may not be rolled back automatically, requiring manual intervention.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How does Active Record handle reversible migrations, and what is the purpose of the reversible method?

A

Active Record supports reversible migrations to ensure that changes can be easily undone. The reversible method allows defining actions for both the forward (up) and backward (down) directions of the migration. This ensures that migrations can be rolled back cleanly, restoring the database to its previous state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What are some techniques for generating migrations in Ruby on Rails, and how do they simplify the process of schema modification?

A

Ruby on Rails provides generators for creating migrations, which automate the generation of migration files based on specified changes to the schema. These generators create migration files with appropriate timestamps and boilerplate code, reducing the manual effort required to manage schema modifications.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How does the create_table method in migrations facilitate the creation of database tables, and what are some common options used with this method?

A

The create_table method in migrations allows for the creation of new database tables along with their respective columns. This method automatically generates a primary key column called id by default and supports options such as index, comment, and primary_key for customizing table creation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the purpose of the change_table method in migrations, and how does it differ from create_table?

A

The change_table method in migrations is used to modify existing database tables. Unlike create_table, which creates a new table, change_table allows for in-place modifications such as adding or removing columns, renaming columns, or adding indexes to an existing table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How does the add_column method simplify the process of adding new columns to database tables in migrations?

A

The add_column method in migrations streamlines the process of adding new columns to database tables. It takes care of generating the appropriate SQL statements for adding columns with specified names and data types, reducing the need for manual SQL writing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What is the significance of references in migrations, and how does Rails handle associations using the references keyword?

A

References in migrations facilitate the creation of foreign key columns, which establish associations between different database tables. Rails provides a references keyword that generates foreign key columns along with appropriate indexes, simplifying the creation of associations between models.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

How does Rails support polymorphic associations in migrations, and what is the purpose of the polymorphic option?

A

Rails allows for the creation of polymorphic associations in migrations using the references keyword with the polymorphic option. This option generates additional columns to support polymorphic associations, enabling a single association to link to multiple types of records.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What is the purpose of adding foreign key constraints in database tables?

A

Foreign key constraints guarantee referential integrity by ensuring that a row in one table exists where a specific column matches a corresponding value in another table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How can you add a foreign key constraint using Rails migrations?

A

You can add a foreign key constraint using the add_foreign_key method in Rails migrations. For example, add_foreign_key :articles, :authors adds a constraint to the articles table, referencing the id column of the authors table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What options can be used with the add_foreign_key method in Rails migrations?

A

Options such as column, primary_key, name, on_delete, if_not_exists, validate, and deferrable are supported by the add_foreign_key method. These options provide flexibility in specifying the details of the foreign key constraint.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How can you remove a foreign key constraint using Rails migrations?

A

You can remove a foreign key constraint using the remove_foreign_key method in Rails migrations. For example, remove_foreign_key :accounts, :branches removes the foreign key constraint from the accounts table.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

Does Active Record support composite foreign keys?

A

No, Active Record only supports single column foreign keys. For composite foreign keys, you need to use execute and structure.sql. See the “Schema Dumping and You” section for more details.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How does Rails handle migrations in different environments?

A

By default, Rails migrations run in the development environment. You can specify a different environment using the RAILS_ENV environment variable. For example, bin/rails db:migrate RAILS_ENV=test runs migrations in the test environment.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What is the purpose of the db:schema:load task in Rails?

A

The db:schema:load task loads the database schema from either db/schema.rb or db/structure.sql. It is useful for quickly setting up a new database instance with the current schema.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Why is it recommended to check the schema file into source control?

A

Checking the schema file into source control ensures that all developers working on the project have access to the latest version of the database schema. It also helps in resolving merge conflicts and accurately represents the database structure.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How does Rails provide support for adding seed data to the database?

A

Rails provides a built-in seeds feature, where you can add initial data to the database by writing Ruby code in db/seeds.rb. Running bin/rails db:seed executes this code to populate the database with seed data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What is the purpose of the revert method in Rails migrations?

A

The revert method allows you to undo previous migrations either in whole or in part. It specifies what to do when running a migration and what to do when reverting it, ensuring that instructions are executed in the correct order.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

What is the purpose of validations in Rails applications?

A

Validations in Rails applications ensure that only valid data is saved into the database, helping maintain data integrity.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

What are the advantages of model-level validations over other validation methods?

A

Model-level validations are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How do database constraints compare to model-level validations?

A

Database constraints make validation mechanisms database-dependent and can complicate testing and maintenance, but they can handle some things like uniqueness in heavily-used tables more safely.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What are some drawbacks of using controller-level validations?

A

Controller-level validations can become unwieldy and difficult to test and maintain, making it preferable to keep controllers simple whenever possible.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

When does validation typically occur in Rails?

A

Validations are typically run before INSERT or UPDATE operations are sent to the database, ensuring that only valid objects are stored.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What methods trigger validations in Rails?

A

Methods like create, create!, save, save!, update, and update! trigger validations and save the object to the database only if it’s valid.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

How can you skip validations in Rails?

A

Certain methods like save(validate: false) or methods like decrement!, increment!, and update_all can skip validations, but they should be used with caution.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

What is the purpose of the valid? and invalid? methods in Rails?

A

The valid? method triggers validations and returns true if no errors were found in the object, while invalid? is the inverse, returning true if any errors were found.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

How can you access validation errors in Rails?

A

Validation errors can be accessed through the errors instance method, which returns a collection of errors for the object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What are some common validation helpers provided by Active Record?

A

Active Record provides validation helpers like presence, length, numericality, uniqueness, and more, which can be used to define common validation rules for attributes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

What is the purpose of validates_associated in Rails models?

A

validates_associated is used when your model has associations that always need to be validated. Every time you try to save your object, valid? will be called on each one of the associated objects.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Can validates_associated be used with all association types in Rails models?

A

Yes, validates_associated will work with all association types in Rails models.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

What happens if you use validates_associated on both ends of associations in Rails models?

A

If you use validates_associated on both ends of associations, they would call each other in an infinite loop, causing an error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What is the default error message for validates_associated?

A

The default error message for validates_associated is “is invalid”. Note that each associated object will contain its own errors collection; errors do not bubble up to the calling model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

What types of objects can validates_associated be used with?

A

validates_associated can only be used with ActiveRecord objects. However, everything up until that point can also be used on any object which includes ActiveModel::Validations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

What is the purpose of validates_each in Rails models?

A

validates_each validates attributes against a block. It doesn’t have a predefined validation function. You should create one using a block, and every attribute passed to validates_each will be tested against it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

How does validates_with differ from other validation helpers in Rails models?

A

validates_with passes the record to a separate class for validation, allowing for more complex validation logic outside the model itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

How can you implement custom validations in Rails models?

A

Custom validations in Rails models can be implemented using custom validators or custom methods. Custom validators are classes that inherit from ActiveModel::Validator, while custom methods can be created within the model and registered using the validate class method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

What are some common options supported by Rails validators?

A

Some common options supported by Rails validators include :allow_nil, :allow_blank, :message, :on, :strict, :if, and :unless.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

How can you display validation errors in Rails views?

A

You can display validation errors in Rails views by checking if the model has any errors using @model.errors.any?, and then iterating through the errors using @model.errors.each. Additionally, Rails form helpers automatically generate error messages for fields with validation errors.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

What is the significance of callbacks in Rails applications?

A

Callbacks in Rails applications allow you to trigger logic at specific moments in an object’s life cycle, such as creation, saving, updating, deletion, validation, or loading from the database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

How can you register callbacks in Rails models?

A

Callbacks in Rails models can be registered using macro-style class methods, blocks, or procs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Provide examples of using macro-style class methods to register callbacks.

A

Examples of using macro-style class methods to register callbacks include before_validation, before_create, after_save, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

Explain the purpose of using blocks and procs in registering callbacks.

A

Blocks and procs can be used in registering callbacks to provide concise inline logic for the callback action.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

How can you define custom callback objects in Rails?

A

Custom callback objects in Rails allow you to define reusable callback logic and register them in models for specific life cycle events.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Why is it recommended to declare callback methods as private?

A

Declaring callback methods as private is recommended to ensure encapsulation and prevent them from being called from outside the model.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

What is the importance of controlling when callbacks are triggered?

A

Controlling when callbacks are triggered is important for managing the flow of logic and ensuring that callbacks execute in the desired context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

Explain the difference between before_create and before_save callbacks.

A

before_create callbacks are triggered specifically before an object is created, while before_save callbacks are triggered before an object is saved (which includes both creation and update operations).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

Why should calls to methods like update or save be avoided within callbacks?

A

Calls to methods like update or save should be avoided within callbacks to prevent unintended side effects and ensure consistency in object state.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

Describe the significance of after_commit and after_rollback callbacks.

A

after_commit callbacks guarantee that the transaction has completed and the data has been persisted to the database, whereas after_save callbacks do not provide such guarantees.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

How does the after_save callback behave in comparison to after_create and after_update?

A

The after_save callback runs on both create and update operations, but always after the more specific callbacks after_create and after_update.

66
Q

Where should before_destroy callbacks be placed for dependent associations?

A

before_destroy callbacks should be placed before dependent associations (dependent: :destroy) to ensure they execute before the associated records are deleted.

67
Q

What guarantees does after_commit provide that after_save doesn’t?

A

after_commit ensures that the data has been persisted to the database and the transaction has completed successfully, providing stronger guarantees than after_save.

68
Q

When is the after_initialize callback triggered?

A

The after_initialize callback is triggered whenever an Active Record object is instantiated, either through new or when loaded from the database.

69
Q

Differentiate between the after_initialize and after_find callbacks.

A

after_initialize is triggered when an object is instantiated, while after_find is triggered when a record is loaded from the database, before after_initialize if both are defined.

70
Q

Explain the purpose of the after_touch callback and provide an example of its usage.

A

The after_touch callback is triggered whenever an Active Record object is touched, allowing you to execute logic when an object is updated.

71
Q

Which methods trigger callbacks related to object creation, updating, and deletion in Rails?

A

Methods like create, save, destroy, update, etc., trigger callbacks related to object creation, updating, and deletion in Rails.

72
Q

In what context is the after_find callback triggered?

A

The after_find callback is triggered when using finder methods like all, first, find, find_by, etc., to load records from the database.

73
Q

When is the after_initialize callback triggered?

A

The after_initialize callback is triggered every time a new object of the class is initialized, whether through new or when loaded from the database.

74
Q

What are dynamic finders in Rails, and how are they related to callbacks?

A

Dynamic finders in Rails are automatically generated methods for every attribute, allowing you to find records by specific attribute values. They are related to callbacks as they trigger the after_find callback when used.

75
Q

Why should the skipping of callbacks be approached with caution?

A

Skipping callbacks should be approached cautiously because critical business rules and application logic may be dependent on them. Bypassing callbacks without understanding the potential implications can lead to invalid data.

76
Q

How is execution halted in a callback chain in Rails?

A

Execution in a callback chain can be halted by using the throw :abort statement. This stops the chain and issues a ROLLBACK command if inside a transaction.

77
Q

What happens if an exception is raised within a callback chain?

A

If an exception, other than ActiveRecord::Rollback or ActiveRecord::RecordInvalid, is raised within a callback chain, it will be re-raised by Rails after the chain is halted.

78
Q

Explain how relational callbacks work in Rails models.

A

Relational callbacks in Rails models allow callbacks to be defined based on model relationships. For example, you can specify that associated records should be destroyed when a parent record is destroyed.

79
Q

What are association callbacks, and how are they defined?

A

Association callbacks in Rails are triggered by events in the life cycle of a collection. They are defined by adding options to the association declaration, such as before_add, after_add, before_remove, and after_remove.

80
Q

How can conditional callbacks be implemented in Rails?

A

Conditional callbacks in Rails can be implemented using the :if and :unless options, which accept a symbol, a Proc, or an array. These options allow you to specify conditions under which a callback should or should not be executed.

81
Q

Provide examples of using the :if and :unless options with callbacks.

A

Examples include associating the :if and :unless options with a symbol corresponding to the name of a predicate method, with a Proc object, or with an array of procs or method names as symbols.

82
Q

What are callback classes in Rails, and how are they useful?

A

Callback classes in Rails allow encapsulation of callback methods for reuse across multiple models. They can be instantiated as objects or declared as class methods.

83
Q

Explain the purpose of transaction callbacks in Rails models.

A

Transaction callbacks in Rails, such as after_commit and after_rollback, are triggered upon the completion of a database transaction. They are useful for interactions with external systems and ensuring data consistency.

84
Q

What aliases exist for the after_commit callback, and how do they differ?

A

Aliases for the after_commit callback include after_create_commit, after_update_commit, and after_destroy_commit, which are specific to create, update, and destroy operations, respectively. Additionally, there’s after_save_commit, which encompasses both create and update operations together.

85
Q

What is the default ordering of transactional callbacks in Rails, and how can it be configured?

A

By default, transactional callbacks in Rails run in the order they are defined. However, they can be configured to run in reverse order by setting config.active_record.run_after_transaction_callbacks_in_order_defined to false.

86
Q

Why do we need associations between models in Rails?

A

Associations between models in Rails simplify common operations by establishing connections between Active Record models. This simplification streamlines tasks such as creating, updating, and deleting associated records.

87
Q

What are the six types of associations supported in Rails?

A

The six types of associations supported in Rails are:

belongs_to
has_one
has_many
has_many :through
has_one :through
has_and_belongs_to_many

88
Q

How is a belongs_to association different from a has_one association?

A

A belongs_to association sets up a one-to-one connection where each instance of the declaring model “belongs to” one instance of the other model. On the other hand, a has_one association indicates that one other model has a reference to this model. The main difference lies in where the foreign key is located: in a belongs_to association, the foreign key is on the table for the declaring model, while in a has_one association, the foreign key is located in the other table.

89
Q

When should you use has_many :through instead of has_and_belongs_to_many?

A

You should use has_many :through when you need to work with the relationship model as an independent entity, or when you require validations, callbacks, or extra attributes on the join model. On the other hand, has_and_belongs_to_many is simpler and more suitable when you don’t need to interact directly with the join model.

90
Q

What is the purpose of polymorphic associations in Rails?

A

Polymorphic associations allow a model to belong to more than one other model, on a single association. This flexibility enables instances of a model to be associated with instances of multiple other models, enhancing the versatility of database relationships.

91
Q

How can Rails infer primary key-foreign key information for associations with composite primary keys?

A

Rails can infer primary key-foreign key information for associations with composite primary keys if the composite primary key contains the :id column and the column is unique for all records. If the model’s composite primary key does not contain the :id column, or if the :id column is not unique for all records, you can specify the query_constraints option on the association to use the full composite primary key in associations.

92
Q

What is a self-join, and when might you use it in Rails?

A

A self-join is a type of association where a model establishes a relation to itself. This is useful when modeling hierarchical relationships within a single database model, such as tracing relationships between managers and subordinates in an employee structure. In a self-join, a model can have associations with instances of the same model, allowing for complex hierarchical structures to be represented.

93
Q

What is the purpose of controlling caching in Active Record associations?

A

Controlling caching ensures that the most recent query results are available for further operations, optimizing performance by avoiding unnecessary database queries.

94
Q

What precautions should you take to avoid name collisions in association naming?

A

Avoid using names for associations that are already used for instance methods of ActiveRecord::Base, as it can lead to method overriding and break functionality. For example, attributes like attributes or connection should be avoided.

95
Q

Why is it necessary to update the schema when working with associations in Rails?

A

It’s essential to update the database schema to match associations. For belongs_to associations, foreign keys need to be created, while for has_and_belongs_to_many associations, the appropriate join table must be generated. This ensures referential integrity and proper functioning of associations.

96
Q

What is the purpose of the has_one association in Rails?

A

The has_one association in Rails creates a one-to-one relationship with another model, indicating that the other class contains the foreign key.

97
Q

What are the six methods added to a class with a has_one association?

A

The six methods added to a class with a has_one association are:
association
association=
build_association
create_association
create_association!
reload_association
reset_association

98
Q

Can you explain the purpose of the association method in a has_one association?

A

The association method returns the associated object, if any, or nil if no associated object is found.

99
Q

What does the build_association method do in a has_one association?

A

The build_association method returns a new object of the associated type, instantiated with the passed attributes, and sets the link through its foreign key but does not save the associated object.

100
Q

When using create_association, under what conditions will the associated object be saved?

A

The create_association method returns a new object of the associated type, instantiated with the passed attributes, sets the link through its foreign key, and saves the associated object after passing all validations specified on the associated model.

101
Q

How does create_association! differ from create_association?

A

create_association! does the same as create_association, but it raises ActiveRecord::RecordInvalid if the record is invalid.

102
Q

What options are available for customizing the behavior of a has_one association?

A

Options available for customizing the behavior of a has_one association include:
:as
:autosave
:class_name
:dependent
:foreign_key
:inverse_of
:primary_key
:required
:touch
:validate

103
Q

Explain the purpose of the autosave option in a has_one association.

A

The autosave option, when set to true, ensures that Rails will save any loaded association members and destroy members marked for destruction whenever you save the parent object.

104
Q

When using the foreign_key option in a has_one association, what does it allow you to specify?

A

The foreign_key option in a has_one association allows you to specify the name of the foreign key directly, overriding the default convention where Rails assumes the column name is the name of the model with the suffix _id added.

105
Q

When are objects saved in a has_many association?

A

Objects in a has_many association are automatically saved when assigned to the association.

106
Q

What happens if the parent object in a has_many association is unsaved?

A

If the parent object is unsaved, child objects are not saved when added, but they are automatically saved when the parent is saved.

107
Q

How can you assign an object to a has_many association without saving it?

A

To assign an object to a has_many association without saving it, use the collection.build method.

108
Q

What does the has_and_belongs_to_many association create?

A

The has_and_belongs_to_many association creates a many-to-many relationship with another model using an intermediate join table.

109
Q

What methods are added by has_and_belongs_to_many?

A

Methods added by has_and_belongs_to_many include collection, collection«, collection.delete, collection.destroy, collection=, and more.

110
Q

What does the collection method return?

A

The collection method returns a Relation of all associated objects.

111
Q

How can you add objects to a collection in a has_and_belongs_to_many association?

A

Objects can be added to a collection in a has_and_belongs_to_many association using collection«, collection.concat, or collection.push.

112
Q

What does the collection.delete method do?

A

The collection.delete method removes objects from the collection by deleting records in the join table.

113
Q

How does the collection.destroy method differ from collection.delete?

A

The collection.destroy method removes objects from the collection by deleting records in the join table, but it does not destroy the objects.

114
Q

What does the collection= method do?

A

the collection= method makes the collection contain only the supplied objects, adding and deleting as appropriate.

115
Q

How can you get the ids of objects in the collection?

A

The collection_singular_ids method returns an array of the ids of objects in the collection.

116
Q

What does the collection.clear method do?

A

The collection.clear method removes every object from the collection by deleting rows from the joining table, without destroying associated objects.

117
Q

How can you check if a collection is empty?

A

The collection.empty? method returns true if the collection does not contain any associated objects.

118
Q

What does the collection.size method return?

A

The collection.size method returns the number of objects in the collection.

119
Q

How does the collection.find method work?

A

he collection.find method finds objects within the collection’s table.

120
Q

What does the collection.where method do?

A

The collection.where method finds objects within the collection based on the supplied conditions.

121
Q

How does the collection.exists? method work?

A

The collection.exists? method checks whether an object meeting the supplied conditions exists in the collection’s table.

122
Q

What does the collection.build method do?

A

The collection.build method returns a new object of the associated type without saving it.

123
Q

What does the collection.create method do?

A

The collection.create method returns a new object of the associated type and saves it.

124
Q

How does collection.create! differ from collection.create?

A

collection.create! raises ActiveRecord::RecordInvalid if the record is invalid, whereas collection.create does not.

125
Q

What is the Active Record Query Interface?

A

The Active Record Query Interface provides a way to interact with the database without directly using SQL queries in most cases. It abstracts away the need for SQL and provides a consistent method format across different database systems.

126
Q

What are some examples of models used in the Active Record Query Interface guide?

A

Examples of models include Author, Book, Customer, Order, Review, and Supplier.

127
Q

How does Active Record handle queries across different database systems?

A

Active Record is compatible with various database systems like MySQL, MariaDB, PostgreSQL, and SQLite, ensuring that the method format remains the same regardless of the underlying database.

128
Q

What are some of the primary finder methods provided by Active Record?

A

Some primary finder methods include find, find_by, take, first, and last.

129
Q

What is the purpose of the find method?

A

The find method retrieves an object corresponding to the specified primary key or a set of primary keys. It raises an ActiveRecord::RecordNotFound exception if no matching record is found.

130
Q

How does the take method differ from the first and last methods?

A

The take method retrieves a record without any implicit ordering and returns nil if no record is found. It does not raise an exception. In contrast, first and last methods find the first and last records ordered by the primary key, respectively, and may raise an ActiveRecord::RecordNotFound exception if no matching record is found.

131
Q

What does the find_by method do?

A

The find_by method finds the first record matching specified conditions and returns nil if no matching record is found. It is equivalent to applying where and take.

132
Q

What options are available for retrieving records in batches using find_each and find_in_batches?

A

Options include batch_size, start, finish, and error_on_ignore. batch_size determines the number of records retrieved in each batch, start specifies the beginning ID for selection, finish specifies the ending ID, and error_on_ignore determines whether an error should be raised if a specific order is present in the relation.

133
Q

How does find_each differ from find_in_batches?

A

find_each yields records individually to the block, while find_in_batches yields batches of records as an array to the block.

134
Q

Why might it be impractical to use Customer.all.each for iterating over a large set of records?

A

Using Customer.all.each can consume excessive memory for large tables since it fetches the entire table in a single pass and keeps the entire array of model objects in memory, which may exceed available memory.

135
Q

What are the different methods available in ActiveRecord for specifying conditions in a query?

A

Answer: ActiveRecord provides several methods for specifying conditions in a query:

Pure String Conditions
Array Conditions
Placeholder Conditions
Hash Conditions

136
Q

How can you ensure safety against SQL injection when using ActiveRecord’s array conditions?

A

To ensure safety against SQL injection when using array conditions, it’s important to use the question mark (?) placeholder syntax for variables and pass them as additional arguments to the where method. For example, Book.where(“title = ?”, params[:title]) ensures that the variable params[:title] is safely sanitized and escaped before being included in the SQL query.

137
Q

How can you specify conditions that use the LIKE operator in ActiveRecord, and what precautions should be taken?

A

Conditions that use the LIKE operator in ActiveRecord can be specified using array conditions. However, it’s important to note that SQL LIKE wildcards (% and _) are not automatically escaped. To avoid SQL injection vulnerabilities and unexpected behavior, the sanitize_sql_like method should be used to escape wildcard characters in the relevant portion of the argument. For example, Book.where(“title LIKE ?”, Book.sanitize_sql_like(params[:title]) + “%”) ensures that wildcard characters in params[:title] are properly escaped before being included in the SQL query.

138
Q

What does the none method in ActiveRecord return, and in what scenarios is it useful?

A

The none method returns a chainable relation with no records. It generates an empty relation that can be further chained with conditions. This method is useful in scenarios where you need a chainable response to a method or a scope that could return zero results, ensuring that subsequent conditions continue generating empty relations.

139
Q

How does the readonly method in ActiveRecord prevent modification of records, and what exception does it raise when modification is attempted?

A

The readonly method in ActiveRecord explicitly disallows modification of any of the returned objects. When an attempt is made to alter a readonly record, it raises an ActiveRecord::ReadOnlyRecord exception, preventing any changes from being saved to the database.

140
Q

What is optimistic locking in ActiveRecord, and how does it handle conflicts during record updates?

A

Optimistic locking in ActiveRecord allows multiple users to access the same record for edits and assumes a minimum of conflicts with the data. It works by checking whether another process has made changes to a record since it was opened. If a conflict is detected, ActiveRecord raises an ActiveRecord::StaleObjectError exception, indicating that the update has failed. Developers are then responsible for handling the conflict by rescuing the exception and implementing appropriate conflict resolution logic.

141
Q

What is eager loading in Ruby on Rails?

A

Eager loading is a mechanism in Ruby on Rails for loading associated records of objects returned by Model.find using as few queries as possible.

142
Q

What is the “N + 1 Queries Problem” in Ruby on Rails, and how does it occur?

A

The “N + 1 Queries Problem” occurs when multiple queries are executed unnecessarily for each record fetched. For example, fetching 10 books and then executing a separate query for each book’s author.

143
Q

How can you solve the “N + 1 Queries Problem” using Active Record in Ruby on Rails?

A

The “N + 1 Queries Problem” can be solved using methods like includes, preload, and eager_load in Active Record, which allow specifying in advance all the associations that are going to be loaded.

144
Q

What is the difference between includes, preload, and eager_load in Ruby on Rails?

A

includes: Ensures that all specified associations are loaded using the minimum possible number of queries.
preload: Loads each specified association using one query per association.
eager_load: Loads all specified associations using a LEFT OUTER JOIN.

145
Q

How can you eager load multiple associations with a single Model.find call in Ruby on Rails?

A

Multiple associations can be eager loaded with a single Model.find call using an array, hash, or a nested hash of array/hash with the includes method.

146
Q

What is strict_loading in Ruby on Rails, and how can you enable it?

A

trict_loading is a feature in Ruby on Rails that prevents lazy loading of associations. It can be enabled on a relation or a record using methods like strict_loading! and specifying a mode argument.

147
Q

What are scopes in Ruby on Rails, and how are they defined?

A

Scopes in Ruby on Rails allow specifying commonly-used queries which can be referenced as method calls on the association objects or models. They are defined using the scope method inside the class, passing the query as a lambda.

148
Q

How can arguments be passed to scopes in Ruby on Rails?

A

Scopes in Ruby on Rails can take arguments by defining them within the lambda passed to the scope method. These arguments can then be passed when calling the scope as if it were a class method.

149
Q

What is a default scope in Ruby on Rails, and how is it applied?

A

A default scope in Ruby on Rails is a scope that is applied across all queries to the model. It is defined using the default_scope method within the model itself, and it modifies the SQL queries executed on the model.

150
Q

How can you remove all scoping from a query in Ruby on Rails?

A

All scoping can be removed from a query in Ruby on Rails using the unscoped method. This is especially useful if a default scope is specified in the model and should not be applied for a particular query.

151
Q

What is an enum in the context of Rails models?

A

An enum in Rails allows you to define a set of symbolic values for an attribute of a model.

152
Q

What is the purpose of declaring an enum in a Rails model?

A

Declaring an enum in a Rails model allows you to easily reference symbolic values instead of raw integers in your code.

153
Q

How does Rails automatically create scopes for enums?

A

Rails automatically creates scopes for enums, making it convenient to query objects based on enum values.

154
Q

Can you explain how instance methods are automatically created for enums in Rails models?

A

Instance methods are automatically created for enums in Rails models to check and change the value of the enum attribute.

155
Q

What is the significance of the find_or_create_by method in Rails?

A

The find_or_create_by method in Rails is used to find a record with specified attributes, or create it if it doesn’t exist.

156
Q

How does find_or_create_by differ from find_or_create_by!?

A

find_or_create_by! behaves similarly to find_or_create_by, but it raises an exception if the new record is invalid.

157
Q

What is the purpose of the find_or_initialize_by method in Rails?

A

The find_or_initialize_by method in Rails is used to find a record with specified attributes, or initialize a new instance if it doesn’t exist.

158
Q

How does pluck differ from other methods like select in Rails?

A

pluck directly converts database results into Ruby arrays, without constructing ActiveRecord objects, leading to potential performance benefits.

159
Q

What is the difference between pluck and pick in Rails?

A

pluck returns an array of values for specified columns, while pick returns the first row of specified column values as a single object.

160
Q

How can you use the exists? method in Rails to check for the existence of records?

A

The exists? method in Rails is used to check for the existence of records in a database table.

161
Q

What are some examples of using calculations like count, average, minimum, maximum, and sum in Rails?

A

Calculations like count, average, minimum, maximum, and sum in Rails are used to perform aggregate operations on database tables.

162
Q

How can you run EXPLAIN on a Rails relation, and what information does it provide?

A

You can run EXPLAIN on a Rails relation to get information about how the database executes a query, including the query plan.

163
Q

What are some options you can pass to EXPLAIN for deeper analysis?

A

Options such as :analyze and :verbose can be passed to EXPLAIN for deeper analysis of the query execution plan.