【问题标题】:Rails have ActiveRecord grab more than one association in one go?Rails 让 ActiveRecord 一次性抓取多个关联?
【发布时间】:2015-07-06 15:26:21
【问题描述】:

下面的问题有一个很好的答案,可以使用Comment.includes(:user) 在一次点击中获取活动记录集合的关联值。当您有多个关联想一次性抓取时怎么办?

Rails have activerecord grab all needed associations in one go?

像下面Customer.includes(:user).includes(:sales).includes(:prices) 那样将它们链接在一起是最好的方法,还是有更清洁的方法。

此外,当我在索引表的循环中执行此操作时。我可以在customer.rb 模型上添加一个方法,以便我可以调用@customers.table_includes 等并拥有

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

作为记录,我测试了上述内容,但它不起作用,因为它是一个集合上的方法(尚未弄清楚如何做到这一点)。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    在回答这个问题时,我假设 usersalesprices 都是来自 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 这样非常通用的名称可能不太友好。

    【讨论】:

    • 谢谢。我把它作为一个范围包括在内,并且工作得非常好。我已经包含,所以我没有在每个循环上调用数据库。似乎joins 将返回查询数据库。有没有办法同时加入和包含,或者只是在范围内链接?
    • 你假设表是 activerecord 与 has_many 和 belongs_to 等相关联的假设是“是”。
    • 到目前为止,使用scope :table_includes, -&gt; { joins(:user, :sales, :prices).includes(:user, :sales, :prices) } 似乎有效,但不是很干。希望我可以在一次通话中替代joinsincludes
    • 我猜joins 如果您要连接同一张桌子上的几张桌子,那将没有多大意义。 (抱歉,想得不够清楚。)这将创建一个不必要地重复许多行的记录集。我会将其保留在includes,以便分别加载每个关联。这可能与您将获得的一样好。
    • 干杯。生病坚持包括然后。也可以将其重命名为includes_for_table_partial,甚至可以将其放在装饰器中,因为它与视图有关。再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多