Join Kevin Skoglund for an in-depth discussion in this video Understanding ActiveRecord and ActiveRelation, part of Ruby on Rails 4 Essential Training.
ActiveRecord and ActiveRelation are the part of the Rails framework that's going to power our models. So before we begin coding our models, let's get a big picture understanding of ActiveRecord and ActiveRelation. active record when it's written all lower case as 2 separate words refers to a commonly used design pattern for working with relational databases. It is not Rails specific. You can use the active record pattern in any programming language. It's an approach to designing object-oriented software. ActiveRecord, when it's written as one word with a capital A and R, refers to the rails implementation of the Active Record pattern.
Often you can use these terms interchangeably, but it helps to understand the context, and to know the difference. The ActiveRecord design pattern allows us to retrieve database data as objects and to work with them in an object oriented way not just as static rows of data. If you've ever worked with database data as rows, you know that it can be cumbersome. Instead, ActiveRecord makes our objects intelligent. The objects understand the structure of the database and they know how to interact with it. Our objects not only contain data, but they also contain code for creating, reading, updating, and deleting rows in the database.
Therefore, objects can be manipulated and saved back to the database with just a few simple commands. Let's see an example to give you a feel for it. In this example, I start out by setting the variable user equal to a new instance of the class user, which is going to be an ActiveRecord class. Next, I set the attribute for first name equal to Kevin, then I can call user dot save. With that one simple command, I've now written an SQL insert statement, and inserted that row into the database. This is much easier than writing raw SQL, especially once our objects become much more complex.
Next I set the attribute last name equal to Skoglund then I called user.save again this time instead of doing an insert statement, Rails does an SQL update statement because the active record object keeps track of the fact that this object has already been stored in the database. So it not only constructs the SQL for us. It creates smart choices about what kind of SQL to write. And then last, I call user.delete. Which writes an SQL delete statement. Which deletes this row from the database. With just these few simple commands, I can work with my database data in an object oriented way.
It's easy to use and it's easy to understand. I can let the objects handle writing all the SQL statements for me to get the job done. And that's what I mean by intelligent objects. Next, let's talk about ActiveRelation. ActiveRelation was added in Rails version 3. It's often referred to as "ARel" which is short for ActiveRelation. ActiveRelation is an object-oriented interpretation of relational algebra. Now the odds are very strong that you're not an expert in relational algebra, so let me describe it to you in a different way. ActiveRelation simplifies the generation of complex database queries.
It allows us to write small queries which can be chained one after another like most Ruby objects. It takes care of handling complex joins and aggregation, and uses efficient SQL to do it. It also manages the timing of when queries are executed. Queries don't execute until we actually need them. ActiveRelation is going to be used heavily by ActiveRecord for queries and for managing the relationships between our objects. You can think of ActiveRelation as the sort of underpinning of ActiveRecord. ActiveRecord sort of sits on top of it.
ActiveRelation mostly lives behind the scenes, but it's important to understand what it does for us. Let me give an example to show how simple it is to construct queries using ActiveRelation. We'll talk more about the query syntax later in this chapter. But this will at least give you a taste for it. First, I'm going to find all users. Where the first name is equal to Kevin. In the second line, I'm going to add to that query. I'm going to say that the query should also be ordered by the last name and the results should be limited to just 5. Then in the third line, I'm going to include the articles that were authored by this user in those search returns.
Notice how I'm breaking the query into discrete segments, and then daisy chaining those segments together. At the end, ActiveRelation puts the pieces together and writes one SQL statement for the composite version. The example I show is probably not the exact SQL that I would write, but this gives you the idea of how it constructs complex SQL from small segments. When we start doing complicated work, joining lots of tables together and aggregating data, ActiveRelation will manage that complexity for us. And our code will never become much more complex then this example code.
Alright. Now that you have the big picture in your head, let's get our hands dirty working with our models.
- Why use Ruby on Rails?
- Installing Ruby on Rails on Mac and Windows
- Rendering templates and redirecting requests
- Generating and running database migrations
- Creating, updating, and deleting records
- Understanding association types
- Using layouts, partials, and view helpers
- Incorporating assets using asset pipeline
- Validating form data
- Authenticating users and managing user access
- Architecting RESTful applications
- Debugging and error handing
Skill Level Beginner
1. What Is Ruby on Rails?
2. Installing Ruby on Rails on a Mac
3. Installing Ruby on Rails on a Windows Machine
4. Getting Started
5. Controllers, Views, and Dynamic Content
6. Databases and Migrations
7. Models, ActiveRecord, and ActiveRelation
9. Controllers and CRUD
10. Layouts, Partials, and View Helpers
13. Data Validation
14. User Authentication
15. Improving the Simple CMS
16. REST and RESTful Routes
17. Debugging and Error Handling
18. Introducing More Advanced Topics
Next steps1m 40s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.