The Rails Guides: Active Record Flashcards
What is Active Record?
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.
What is the Active Record Pattern?
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.
What is Object-Relational Mapping (ORM)?
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.
What is Convention over Configuration in Active Record?
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.
What are some mechanisms provided by Active Record as an ORM framework?
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 does Active Record handle naming conventions for models and database tables?
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”.
What are some schema conventions used by Active Record for database columns?
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 can you create Active Record models in Rails?
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 can you override naming conventions in Active Record?
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.
What are some CRUD operations provided by Active Record?
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 does Active Record perform validations?
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.
What are callbacks in Active Record?
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.
What are migrations in Rails?
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 do associations work in Active Record?
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.
What is an overview of migrations in database schema evolution?
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 does Active Record manage database schema evolution over time?
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.
What is the purpose of the db/schema.rb file in the context of database migrations?
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.
What is the role of transactions in database migrations, and how do they affect migration rollbacks?
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 does Active Record handle reversible migrations, and what is the purpose of the reversible method?
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.
What are some techniques for generating migrations in Ruby on Rails, and how do they simplify the process of schema modification?
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 does the create_table method in migrations facilitate the creation of database tables, and what are some common options used with this method?
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.
What is the purpose of the change_table method in migrations, and how does it differ from create_table?
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 does the add_column method simplify the process of adding new columns to database tables in migrations?
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.
What is the significance of references in migrations, and how does Rails handle associations using the references keyword?
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 does Rails support polymorphic associations in migrations, and what is the purpose of the polymorphic option?
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.
What is the purpose of adding foreign key constraints in database tables?
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 can you add a foreign key constraint using Rails migrations?
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.
What options can be used with the add_foreign_key method in Rails migrations?
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 can you remove a foreign key constraint using Rails migrations?
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.
Does Active Record support composite foreign keys?
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 does Rails handle migrations in different environments?
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.
What is the purpose of the db:schema:load task in Rails?
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.
Why is it recommended to check the schema file into source control?
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 does Rails provide support for adding seed data to the database?
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.
What is the purpose of the revert method in Rails migrations?
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.
What is the purpose of validations in Rails applications?
Validations in Rails applications ensure that only valid data is saved into the database, helping maintain data integrity.
What are the advantages of model-level validations over other validation methods?
Model-level validations are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain.
How do database constraints compare to model-level validations?
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.
What are some drawbacks of using controller-level validations?
Controller-level validations can become unwieldy and difficult to test and maintain, making it preferable to keep controllers simple whenever possible.
When does validation typically occur in Rails?
Validations are typically run before INSERT or UPDATE operations are sent to the database, ensuring that only valid objects are stored.
What methods trigger validations in Rails?
Methods like create, create!, save, save!, update, and update! trigger validations and save the object to the database only if it’s valid.
How can you skip validations in Rails?
Certain methods like save(validate: false) or methods like decrement!, increment!, and update_all can skip validations, but they should be used with caution.
What is the purpose of the valid? and invalid? methods in Rails?
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 can you access validation errors in Rails?
Validation errors can be accessed through the errors instance method, which returns a collection of errors for the object.
What are some common validation helpers provided by Active Record?
Active Record provides validation helpers like presence, length, numericality, uniqueness, and more, which can be used to define common validation rules for attributes.
What is the purpose of validates_associated in Rails models?
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.
Can validates_associated be used with all association types in Rails models?
Yes, validates_associated will work with all association types in Rails models.
What happens if you use validates_associated on both ends of associations in Rails models?
If you use validates_associated on both ends of associations, they would call each other in an infinite loop, causing an error.
What is the default error message for validates_associated?
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.
What types of objects can validates_associated be used with?
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.
What is the purpose of validates_each in Rails models?
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 does validates_with differ from other validation helpers in Rails models?
validates_with passes the record to a separate class for validation, allowing for more complex validation logic outside the model itself.
How can you implement custom validations in Rails models?
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.
What are some common options supported by Rails validators?
Some common options supported by Rails validators include :allow_nil, :allow_blank, :message, :on, :strict, :if, and :unless.
How can you display validation errors in Rails views?
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.
What is the significance of callbacks in Rails applications?
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 can you register callbacks in Rails models?
Callbacks in Rails models can be registered using macro-style class methods, blocks, or procs.
Provide examples of using macro-style class methods to register callbacks.
Examples of using macro-style class methods to register callbacks include before_validation, before_create, after_save, etc.
Explain the purpose of using blocks and procs in registering callbacks.
Blocks and procs can be used in registering callbacks to provide concise inline logic for the callback action.
How can you define custom callback objects in Rails?
Custom callback objects in Rails allow you to define reusable callback logic and register them in models for specific life cycle events.
Why is it recommended to declare callback methods as private?
Declaring callback methods as private is recommended to ensure encapsulation and prevent them from being called from outside the model.
What is the importance of controlling when callbacks are triggered?
Controlling when callbacks are triggered is important for managing the flow of logic and ensuring that callbacks execute in the desired context.
Explain the difference between before_create and before_save callbacks.
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).
Why should calls to methods like update or save be avoided within callbacks?
Calls to methods like update or save should be avoided within callbacks to prevent unintended side effects and ensure consistency in object state.
Describe the significance of after_commit and after_rollback callbacks.
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.