合并两个ActiveRecord查询结果

时间:2010-08-29 08:14:00

标签: ruby-on-rails activerecord ruby-on-rails-3

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

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

where(:user_id => user.id)

基本上我希望第二个的结果与第一个类似于SQL中的UNION语句一起出现。可以用这种方式在ActiveRecord中完成吗?

我更喜欢使用union而不是必须在字符串中加入所有followed_id并使用sql中的IN子句。

有什么想法吗?

----- ------编辑 我正在寻找一种方法来使用延迟加载

3 个答案:

答案 0 :(得分:30)

这对我有用:

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

答案 1 :(得分:12)

使用relation & relation

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

答案 2 :(得分:0)

这对我很有用:

Rails/ActiveRecord 的更新版本可能本身就支持这种语法。它看起来类似于:

Model.where(foo: 'bar').or.where(bar: 'bar')

或者,您也可以,只需坚持以下方法即可:

Model.where('foo= ? OR bar= ?', 'bar', 'bar')

提到这个link