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.