Note that there are some explanatory texts on larger screens.

plurals
  1. PORails - Eager Load Association on an Association
    primarykey
    data
    text
    <p><strong>EDIT - Using 'includes' generates a SQL 'IN' clause. When using Oracle this has a 1,000 item limit. It will not work for my company. Are there any other solutions out there?</strong></p> <p>Is it possible to eager load an association on an association?</p> <p>For example, let's say I have an Academy class, and an academy has many students. Each student belongs_to student_level</p> <pre><code>class Academy &lt; ActiveRecord::Base has_many :students end class Student &lt; ActiveRecord::Base belongs_to :academy belongs_to :student_level end class StudentLevel &lt; ActiveRecord::Base has_many :students end </code></pre> <p>Is it possible to tailor the association in Academy so that when I load the students, I ALWAYS load the student_level with the student?</p> <p>In other words, I would like the following section of code to produce one or two queries total, not one query for every student:</p> <pre><code>@academy.students.each do |student| puts "#{student.name} - #{student.student_level.level_name}" end </code></pre> <p>I know I can do this if I change students from an association to a method, but I don't want to do that as I won't be able to reference students as an association in my other queries. I also know that I can do this in SQL in the following manner, but I want to know if there's a way to do this without finder_sql on my association, because now I need to update my finder_sql anytime my default scope changes, and this won't preload the association:</p> <pre><code>SELECT students.*, student_levels.* FROM students LEFT JOIN student_levels ON students.student_level_id = student_levels.id WHERE students.academy_id = ACADEMY_ID_HERE </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload