Rails在左连接中包括与条件的关联 [英] Rails includes association with condition in left join
问题描述
我可以在Rails为includes
方法生成的LEFT JOIN
sql中添加一些条件吗? (Rails 4.2.1,postresql).
Can I add some condition to the LEFT JOIN
sql that Rails generate for the includes
method? (Rails 4.2.1, postresql).
我需要使所有(!)用户具有预加载的关联(当我要查看评论,帖子等的视图计数时,不是N + 1),但是关联需要通过某些条件进行过滤.
I need to get all(!) the users with preloading ( not N+1 when I will puts in a view count of comments, posts and etc) of associations, but associations need to be filtered by some conditions.
示例:
User.includes(:comments)
# => SELECT * FROM users LEFT JOIN comments ON ...
这将返回所有用户并预加载注释(如果存在).
如果要在where
中为注释"关联添加一些条件,则SQL不会返回所有用户,例如:
This will return all the users and preload comments if they exists.
If I will add some conditions for the "comments" association in where
, then SQL doesn't return ALL the users, for example:
User.includes(:comments).where(comments: {published_at: Date.today})
# => SELECT * FROM users LEFT JOIN comments ON ... WHERE comments.published_at = ...
这只会返回今天发表评论的用户.
This will return only users, that have comments, published today.
我需要将条件放入LEFT JOIN
并保存预加载(将对象加载到内存-使用joins
方法进行简单的左联接不会预加载关联).
I need to put conditions inside LEFT JOIN
AND save preloading (load objects to the memory - simple left join with joins
method doesn't preload associations).
SELECT * FROM users LEFT JOIN comments ON (... AND comments.published_at = ...)
那些SQL会正确返回我需要的内容(所有用户及其注释,如果存在的话,将在请求的日期发布)!但是...我无法使用Rails includes
方法生成它,并且'joins'不会预加载关联.
Those SQL will return right what I need (all the users, and their comments, published in requested date, if they exists)! But ... I cant generate it with the Rails includes
method, and `joins' doesn't preload associations.
您对我有什么建议?谢谢!
What do you advice me? Thanks!
推荐答案
Rails在框架库中没有方法可以执行您想要的操作. 不过,这可能会起作用
Rails doesn't have methods in the framework library to do what you want. This might work, though
class User < ActiveRecord::Base
has_many :comments
has_many :recent_comments, -> { where(published_at: Date.today) }, class_name: "Comment"
end
然后查询用户并预加载最近的评论
Then query for Users and preload recent_comments
@users = User.preload(:recent_comments)
这篇关于Rails在左连接中包括与条件的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!