Chapter 3. Active Record
Section 3.0. Introduction Recipe 3.1. Setting Up a Relational Database to Use with Rails Recipe 3.2. Programmatically Defining Database Schema Recipe 3.3. Developing Your Database with Migrations Recipe 3.4. Modeling a Database with Active Record Recipe 3.5. Inspecting Model Relationships from the Rails Console Recipe 3.6. Accessing Your Data via Active Record Recipe 3.7. Retrieving Records with find Recipe 3.8. Iterating Over an Active Record Result Set Recipe 3.9. Retrieving Data Efficiently with Eager Loading Recipe 3.10. Updating an Active Record Object Recipe 3.11. Enforcing Data Integrity with Active Record Validations Recipe 3.12. Executing Custom Queries with find_by_sql Recipe 3.13. Protecting Against Race Conditions with Transactions Recipe 3.14. Adding Sort Capabilities to a Model with acts_as_list Recipe 3.15. Performing a Task Whenever a Model Object Is Created Recipe 3.16. Modeling a Threaded Forum with acts_as_nested_set Recipe 3.17. Creating a Directory of Nested Topics with acts_as_tree Recipe 3.18. Avoiding Race Conditions with Optimistic Locking Recipe 3.19. Handling Tables with Legacy Naming Conventions Recipe 3.20. Automating Record Timestamping Recipe 3.21. Factoring Out Common Relationships with Polymorphic Associations Recipe 3.22. Mixing Join Models and Polymorphism for Flexible Data Modeling |
3.0. Introduction
Active Record provides
Active Record works by creating an object relational mapping (ORM) between the Ruby objects of your application and the rows and columns of your database. This mapping allows you to interact with your database just as you would interact with any other Ruby object, eliminating the need to use SQL to manipulate your data. Instead of working with database rows, you have Ruby objects, and database
The benefits of
A domain model consists of data and a set of rules for how that data interacts with the rest of your application. Active Record allows you to define the logic of your domain model using Ruby. This gives you flexibility when defining the specific business requirements of your data, and having this logic centralized in the model makes adapting to changing requirements much easier.
Active Record, like much of Rails, relies on the concept of "convention over configuration" to simplify setup. For example, Active Record determines the fields of your database, eliminating the need to define basic accessors for each field. Active Record relies on table and field naming conventions to map your database schema into Ruby objects with a minimal amount of configuration. Table
Active Record also provides dynamic attribute-based
In this chapter I'll introduce you to many of the ways that Active Record
|