In part II of this series - Understanding ActiveRecord joins - I'll go through similar exercises to explain when and how we can use ActiveRecord's left_joins. Since then, Rails supports left outer joins through the ActiveRecord methods left_joins and its alias left_outer_joins. Until rails 5 was released, if you wanted to run a left outer join, you'd also have to pass a custom SQL to the joins method. One of the ways we could solve this problem would be to pass an SQL string: Bookings.joins("INNER JOIN accommodations ON accommodations.id = bookings.bookable_id AND bookings.bookable_type = 'Accommodation'") into the table Active Record Static finder methods to wrap commonly used SQL. That is because we need to tell joins which bookable type we want to use since there can be many. The Active Record class typically has methods that do the following. In polymorphic associations if you try joins using symbols, you'll get an error: Booking.joins(:bookable)ĪctiveRecord::EagerLoadPolymorphicError (Cannot eagerly load the polymorphic association :bookable) How to: Using Active Query Index Hints to improve slow query execution Improving Performance Purpose This article is meant to help clarify when and how. ActiveRecord joins in polymorphic associationsĪdding a new polymorphic model Accommocation to our domain: class Accommodation < ApplicationRecord This has the advantage of providing extra flexibility in building more complex queries. Instead of passing symbols that tell ActiveRecord which association to join (and that will be later translated to SQL), the joins method also accepts a SQL string directly as an argument. So next, we filter by payment status using the where method: Guest.joins(bookings: :payment).where(payments: ) The payments data is now available to query. This produces two inner joins: SELECT "guests".* FROM "guests" INNER JOIN "bookings" ON "bookings"."guest_id" = "guests"."id" INNER JOIN "payments" ON "payments"."booking_id" = "bookings"."id"Īnd results in the following joined table: guests.id So what we're saying is: 'Return all guests that have bookings with payments'. Luckily, the ActiveRecord joins method allows us to pass nested associations: Guest.joins(bookings: :payment) Let's use the following domain example to better illustrate this: class Payment Booking -> Payment. You've probably seen a Venn diagram similar to the cover image of this post and that illustrates this combination, where each circle is a table and their intersection represents the common attributes.īut what does this mean in practice? And how can we take advantage of the joined tables? It is useful when you want to query a table based on matching entries from a related table. What is an inner join and when should it be used?Īn inner join lets you combine two tables as long as they have matching values for a common attribute.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |