Ruby-on-rails 合并两个 ActiveRecord 查询结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3594041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:07:12  来源:igfitidea点击:

Combine two ActiveRecord Query results

ruby-on-railsactiverecordruby-on-rails-3

提问by zzawaideh

I currently have two active record queries that I would like to combine together

我目前有两个活动记录查询,我想将它们组合在一起

joins("join relationships ON user_id = followed_id").
              where("follower_id = #{user.id}")

and

where(:user_id => user.id)

Basically I want the results of the second one to appear with the first similar to a UNIONstatement in SQL. Can it be done in ActiveRecord in this way?

基本上我希望第二个的结果与第一个类似,类似于UNIONSQL 中的语句。在ActiveRecord中可以这样实现吗?

I would prefer to use a union rather that have to join all the followed_ids in a string and use the INclause in sql.

我更喜欢使用联合,而不是必须将所有followed_ids 连接到一个字符串中并IN在 sql 中使用子句。

Any ideas?

有任何想法吗?

-----Edit------ I am looking for a way to get this to work with lazy loading

-----编辑------ 我正在寻找一种方法来让它与延迟加载一起工作

采纳答案by fantactuka

Use relation & relation:

使用relation & relation

Model.joins("join relationships ON user_id = followed_id").where("follower_id = {user.id}") & Model.where(:user_id => user.id)

回答by Corentin Geoffray

This was useful for me:

这对我很有用:

Model.where(...) | Model.where(...)