简体   繁体   English

Rails可以一口气抓住ActiveRecord多个关联吗?

[英]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) . 下面的问题很好地回答了使用Comment.includes(:user)一键捕获ActiveRecord集合的关联值。 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? Rails可以一口气捕获所有需要的关联吗?

Is the best way to just chain these together like below Customer.includes(:user).includes(:sales).includes(:prices) or is there a cleaner way. 是将这些链接在一起的最佳方法,例如下面的Customer.includes(:user).includes(:sales).includes(:prices)还是有一种更简洁的方法。

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 我可以在customer.rb模型上添加一个方法,以便可以调用@customers.table_includes等并具有

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 . 在回答这个问题时,我假设usersalesprices都是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. 从长远来看,像table_includes这样的通用名称可能不太友好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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