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

左心房为你撑大大i 提交于 2019-12-11 11:25:58

问题


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).


回答1:


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.



来源:https://stackoverflow.com/questions/29908230/rails-have-activerecord-grab-more-than-one-association-in-one-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!