Note that there are some explanatory texts on larger screens.

plurals
  1. POReusing scopes as filters on `includes` eager-loading
    primarykey
    data
    text
    <p>Breaking it down to a minimal example:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :profiles has_many :addresses, through: :profiles end class Profile &lt; ActiveRecord::Base belongs_to :user has_many :addresses end class Address &lt; ActiveRecord::Base belongs_to :profile def self.active_by_date where(is_active: true).order('updated_at DESC') end end class UsersController &lt; ApplicationController def index @users = User.includes(profiles: :addresses) end end </code></pre> <p>Suppose that in the above controller action, I want to eager-load the active addresses, sorted by date, for each user's profiles. I could do this:</p> <pre><code>class User &lt; ActiveRecord::Base has_many :profiles has_many :addresses, through: :profiles has_many :active_addresses_by_date, through: :profiles, source: :addresses, class_name: Address, conditions: ['address.is_active = ?', true], order: 'address.updated_at DESC' end class UsersController &lt; ApplicationController def index @users = User.includes(profiles: :active_addresses_by_date) end end </code></pre> <p>But since I can't reuse the <code>active_by_date</code> scope on <code>Address</code>, the condition and order now exist in two places. I'd like to DRY this up so that, as in the first version, the concept of "active addresses by date" exists only in the <code>Address</code> model. Ideally, in the view I would be able to call <code>@users.each { |user| user.addresses.active_by_date }</code> without firing any queries. Is this possible under ActiveRecord, and if so, how would I go about it?</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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