【问题标题】:Trouble on eager loading "second degree" associated objects急切加载“二级”关联对象时出现问题
【发布时间】:2012-03-26 15:44:54
【问题描述】:

我正在运行 Ruby on Rails 3.1。我想通过应用一些条件来急切地加载“二级”关联对象,但我遇到了麻烦。

看来我已经通过使用解决了part of my issue

article_categories =
  article
    .categories
    .includes(:comments => [:category_relationships])
    .where(:category_relationships => {:user_id => @current_user.id})

其中涉及的类说明如下:

class Category < ActiveRecord::Base
  has_many :comment_relationships
  has_many :comments,
    :through => :comment_relationships

  ...
end

class Comment < ActiveRecord::Base
  has_many :category_relationships
  has_many :categories,
    :through => :category_relationships

  ...
end

上面的代码(好像做对了):

  1. 通过关注has_many :through :category_relationships 关联(即通过关注.where(:category_relationships =&gt; {:user_id =&gt; @current_user.id}) 条件)加载所有categories
  2. 渴望加载所有article.comments.where(:user_id =&gt; @current_user.id)

不过,我想多做一些:

  1. to order 通过category_relationships 中存在的:position 属性检索categories,以便生成的article_categories 按位置排序;
  2. 急切加载还有category_relationship对象user_id == @current_user.id,因为上面的代码没有做到这一点。

如何利用即时加载来实现这一点?

【问题讨论】:

  • 您在CategoryComment 之间使用两个不同的连接表有什么原因吗?

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


【解决方案1】:

解决办法:

  1. .order("category_relationships.position")

  2. 想象急切加载是带有一些过滤的笛卡尔积,因此“where”正在过滤包含的最终结果(实际上是左连接)。但是可以使用带有子查询的where 来完成,该子查询首先会按用户过滤类别,然后可以删除您的位置。

【讨论】:

  • 你能举个例子吗?
猜你喜欢
  • 1970-01-01
  • 2014-11-14
  • 1970-01-01
  • 2014-04-06
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多