【问题标题】:How to eager loading when there are further conditions on association objects?当关联对象有更多条件时如何进行预加载?
【发布时间】:2012-09-21 17:55:50
【问题描述】:

我正在使用 Ruby on Rails 3.2.2 并且我有以下 has_many :through 关联以便“按类别排序文章”:

class Article < ActiveRecord::Base
  has_many :category_associations                                     # Association objects
  has_many :associated_categories, :through => :category_associations # Associated objects
end

class CategoryAssociation < ActiveRecord::Base
  acts_as_list :scope => 'category_id = #{category_id} AND creator_user_id = #{creator_user_id}'

  belongs_to :associated_article
  belongs_to :creator_user, :foreign_key => 'creator_user_id'
end

在检索 associated_categories 时,我想加载用户创建的 category_associations 对象(注意:创建者用户由 creator_user_id 数据库表中的 creator_user_id 列标识) 因为我需要显示 position 值(注意position 属性,Integer,是 act_as_list gem 所必需的,它是category_associations 数据库表中的列)“靠近”每篇文章的标题。

实际上,在我看来,我想以适当性能的方式制作类似以下的东西(注意:它是假设@articles 中的每篇文章都被用户“分类”——用户指的是category_associations 的创建者用户):

<% @articles.each do |article| %>
  <%= link_to(article.title, article_path(article)) %> (<%= # Display the article position in the given category %>)
<% end %>

也许,我应该“创建”和“处理”一个 自定义数据结构(或者,也许,我应该做一些其他的......),但我不知道如何继续完成什么我正在寻找。


此时我认为急切加载对我的情况来说是一个好方法,因为我可以避免N + 1 queries problem,因为我必须在关联对象上声明更多条件以便:

  • 检索由给定用户创建的关联对象的特定属性值(在我的例子中是指position 值);
  • “关联”(以某种方式,使position 值适合显示)每个特定属性值到对应的关联对象。

【问题讨论】:

  • 带有包含的默认范围?
  • @apneadiving - 你如何用scope 方法做到这一点?你能发布一个例子,因为我的案例(我认为)是一个人为的案例吗?

标签: ruby-on-rails ruby ruby-on-rails-3 associations eager-loading


【解决方案1】:

我想,你正在寻找这个

@articles = Article.includes(:associated_categories)

这将急切加载您的所有文章,包括它的两个关联(关联类别、关联类别)。因此,它将避免 N+1 问题,并且在您遍历 @articles 及其视图中的关联时不会触发查询。

【讨论】:

  • 我正在寻找检索和显示每篇文章的 position 值(假设每篇文章都是由 given 用户 - 关联的创建者用户“与类别相关的” ),也许带有急切加载(如果急切加载在我的情况下是一种“适当”和“高效”的方法)。
  • @user12882:位置从何而来?是否已经存在或者您想动态创建职位编号?
  • position 来自 category_associations:(正如我在问题中所写)position 属性,Integer,是 act_as_list gem 所必需的,它是一个列存在于category_associations 数据库表中。每个关联类别都有一个或多个有序类别关联,并且更多用户可以将一篇文章关联到多个类别。我正在寻找“检索”/“过滤”相关类别和相关类别关联,其中类别关联由给定用户创建
  • @user12882:如果位置来自 category_associations,您可以使用 @articles.each{|article| 访问它们article.category_associations.each{|ca| p ca.位置}}。由于它们已经预先加载,因此不会触发额外的查询。
猜你喜欢
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 1970-01-01
相关资源
最近更新 更多