[英]Rails have ActiveRecord grab more than one association in one go?
下面的问题很好地回答了使用Comment.includes(:user)
一键捕获ActiveRecord集合的关联值。 如果您想一次获得多个关联,该怎么办?
是将这些链接在一起的最佳方法,例如下面的Customer.includes(:user).includes(:sales).includes(:prices)
还是有一种更简洁的方法。
此外,当我在索引表上循环执行此操作时。 我可以在customer.rb
模型上添加一个方法,以便可以调用@customers.table_includes
等并具有
def table_includes
self.includes(:user).includes(:sales).includes(:prices)
end
为了记录,我测试了上面的内容,但由于它是集合上的一种方法(目前仍未弄清楚如何做到这一点),因此无法正常工作。
在回答这个问题时,我假设user
, sales
和prices
都是Customer
关联。
除了链接,您可以执行以下操作:
Customer.includes(:user, :sales, :prices)
在为此创建抽象方面,您确实有几个选择。
首先,您可以创建一个范围:
class Customer < ActiveRecord::Base
scope :table_includes, -> { includes(:user, :sales, :prices) }
end
或者,如果要使其成为一种方法,则应考虑使其成为类级别的方法,而不是实例级别的方法:
def self.table_includes
self.includes(:user, :sales, :prices)
end
我会考虑创建此抽象的目的。 从长远来看,像table_includes
这样的通用名称可能不太友好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.