Rich Association Traversal
Greetings My Friend,
We could gain the ability to add complexity of other attributes and methods inside our section edit's model, we lost something at the same time. We now have to go through an extra step to get from one side of the association over to the other. For example, in our simple, has and belongs to many join, if we wanted to know all of the admin users who could edit a page, we could just request the array of admin users, page dot admin users and we'd get back an array.
It would reach across the join table to the other side of the association but in our rich join, we can't just ask for section's admin users because there is no direct relationship between section and admin user. There's a model that's in between now. We can still do it, we just have to go through that extra step of going through the section edits and looking up each one's admin user. What we really want, is a way to reach across the join easily to be able to access the admin users by just calling section dot admin users like we have in the top line there.
It's clearly possible because the has and belongs to many join does it and we still have the foreign keys in place to make it possible. It's just a question of telling active record about the relationship. So that it can modify the SQL it writes and treat this rich join like a simple join some of the time. Rails gives us a tool for this using has many through. It allows reaching across a rich join and treating it like it's a has and belongs to many join. The first step, is to create the regular functional rich join first like we did in the last movie.
After that, we can add in another relationship using has many through. So for example, with admin user and section, we already have admin user has many section edits to find. That's the first step. You want to make sure you have that relationship in place. Then once you have that, you can set another relationship for admin user has many sections through section edits. See how that works? We're telling it that it can reach through section edits to get to the other side of the relationship. Admin user now has many sections.
It's a has many relationship. We have all the same methods and the same functionality we're used to when we have a has many. It's just doing it by going through the section edits' join table and the same thing is true from the other side. A section has many section edits and then we can have section has many admin users through section edits. Remember, you always want to define both sides of the association.Let's try out has many through. Let's begin by going into our admin user model and we have has many section edits.
CHEERS,
Maitrey Patel
Maitrey Patel
Comments
Post a Comment