急于加载“二级”的问题。相关对象 [英] Trouble on eager loading "second degree" associated objects

查看:41
本文介绍了急于加载“二级”的问题。相关对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am running Ruby on Rails 3.1. I would like to eager loading "second degree" associated objects by applying some conditions, but I am in trouble.

似乎我已经解决了

It seems that I already solved part of my issue by using:

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

上面的代码(它似乎做对了):

The above code (it seems to do it right):


  1. 通过照顾所有类别 has_many:through :category_relationships 关联(即通过关心 .where(:category_relationships => {:user_id => @ current_user.id})条件);

  2. 渴望加载所有 article.comments.where (:user_id => @ current_user.id)

  1. loads all categories by caring the has_many :through :category_relationships association (that is, by caring the .where(:category_relationships => {:user_id => @current_user.id}) condition);
  2. eager loads all article.comments.where(:user_id => @current_user.id).

不过,我想提出一些建议更多:

However, I would like to make some more:


  1. 定购,通过检索到 :position 属性出现在 category_relationships 中,因此生成的 article_categories 按位置排序

  2. 增加负载也是 category_relationship 对象,其中 user_id == @ current_user.id ,因为上面的代码没有做到这一点。

  1. to order retrieved categories by a :position attribute present in category_relationships so that the resulting article_categories are ordered by position;
  2. to eager load also category_relationship objects where user_id == @current_user.id since the above code doesn't make that.

如何利用急切加载的资源来实现这一目标?

推荐答案

解决方案:


  1. .order( category_relationships.position)

  1. .order("category_relationships.position")

想象一下,急切加载是笛卡尔积,并进行了一些过滤,因此 where正在过滤include的最终结果(实际上是左连接)。但这可以通过 where 和子查询来完成,子查询首先将按用户过滤类别,然后可以删除您的位置。

Imagine eager loading is cartessian product with some filtering so "where" is filtering the end result of include (left join really). But it can be done with where with subquery which first will filter categories by user then your where can be removed.

这篇关于急于加载“二级”的问题。相关对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆