简体   繁体   中英

Rails have ActiveRecord grab more than one association in one go?

The question below had a good answer to grab associated values of an activerecord collection in one hit using Comment.includes(:user) . What about when you have multiple associations that you want to grab in one go?

Rails have activerecord grab all needed associations in one go?

Is the best way to just chain these together like below Customer.includes(:user).includes(:sales).includes(:prices) or is there a cleaner way.

Furthermore, when I am doing this on a loop on an index table. Can I add a method on the customer.rb model so that I can call @customers.table_includes etc and have

def table_includes
  self.includes(:user).includes(:sales).includes(:prices)
end

For the record I tested the above and it didn't work because its a method on a collection (yet to figure out how to do this).

In answering this, I'm assuming that user , sales , and prices are all associations off of Customer .

Instead of chaining, you can do something like this:

Customer.includes(:user, :sales, :prices)

In terms of creating an abstraction for this, you do have a couple options.

First, you could create a scope:

class Customer < ActiveRecord::Base
  scope :table_includes, -> { includes(:user, :sales, :prices) }
end

Or if you want for it to be a method, you should consider making it a class-level method instead of an instance-level one:

def self.table_includes
  self.includes(:user, :sales, :prices)
end

I would consider the purpose of creating this abstraction though. A very generic name like table_includes will likely not be very friendly over the long term.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM