本文介绍了导轨具有ActiveRecord的抢超过一气呵成一个关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题下面有一个很好的答案,使用 Comment.includes一击抢一个ActiveRecord收集相关的值(:用户)。那么当你有你想抓住一次过多个关联?

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有ActiveRecord的抢在一个所有需要的团体去?

时,只是这些链在一起,就像下面 Customer.includes的最佳方式(:用户).includes(:销售).includes(:价格)或有更清洁的方式。

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.rb 模型添加一个方法,这样我可以叫 @ customers.table_includes 等,并有

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

我会考虑,虽然创造这种抽象的目的。就像一个非常通用的名称 table_includes 将可能不会很友好长期。

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.

这篇关于导轨具有ActiveRecord的抢超过一气呵成一个关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 21:58