通过不同的命名关联使用条件,同时包括同一个表两次:导轨找到 [英] rails find: using conditions while including same table twice via different named associations

查看:202
本文介绍了通过不同的命名关联使用条件,同时包括同一个表两次:导轨找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有被用户发送给其他用户的帖子。有两种型号 - :职位和:用户,并张贴有以下命名关联关系:

I have posts which are sent by users to other users. There are two models - :post and :user, and :post has the following named associations:

belongs_to :from_user, :class_name => "User", :foreign_key => "from_user_id"
belongs_to :to_user, :class_name => "User", :foreign_key => "to_user_id"

既:用户:后有is_public一栏,这表明无论是单篇文章和/或整个用户配置文件可以是公共或私有

Both :user and :post have "is_public" column, indicating that either a single post and/or the entire user profile can be public or private.

我的目标是要获取的帖子这是公开的,其受助人的公共配置文件列表。同时,我想包含发件人和收件人信息,以尽量减少数据库调用的#。我们面临的挑战是,我有效地通过协会命名为包括同一个表两次,但在我的条件我要确保我只有收件人的is_public列进行筛选。

My goal is to fetch a list of posts which are public AND whose recipients have public profiles. At the same time, I would like to "include" both sender and recipient info to minimize the # of db calls. The challenge is that I am effectively "including" the same table twice via the named associations, but in my "conditions" I need to make sure that I only filter by the recipient's "is_public" column.

我不能做以下,因为条件不接受关联名作为参数:

I can't do the following because "conditions" does not accept an association name as a parameter:

Post.find(:all, :include => [ :to_user, :from_user ], 
  :conditions => { :is_public => true, :to_user => { :is_public => true }})

所以,有这样我可以做到这一点是通过在用户表做一个额外的加盟:

So, one way I can accomplish this is by doing an additional "join" on the "users" table:

Post.find(:all, :include => [ :to_user, :from_user ], 
  :joins => "inner join users toalias on posts.to_user_id = toalias.id", 
  :conditions => { :is_public => true, 'toalias.is_public' => true })

有没有更好的,也许是更清洁,方式做到这一点?

Is there a better, perhaps cleaner, way to do this?

在此先感谢

推荐答案

我一直没能找到一个比一个原本在我的问题说一个更好的解决方案。这一个不取决于如何编译查询时的Rails名称/别名表和因此似乎比其它的清洁剂(使用第三方宝石或插件的简称):

I have not been able to find a better solution than the one originally stated in my question. This one doesn't depend on how Rails names/aliases tables when compiling a query and therefore appears to be cleaner than the alternatives (short of using 3rd party gems or plugins):

Post.find(:all, :include => [ :to_user, :from_user ],
:joins => "inner join users toalias on posts.to_user_id = toalias.id", 
:conditions => { :is_public => true, 'toalias.is_public' => true })

这篇关于通过不同的命名关联使用条件,同时包括同一个表两次:导轨找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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