在Rails中包含:如何在同一查询中混合OR和外连接?

时间:2014-03-14 15:30:02

标签: ruby-on-rails activerecord

我试图使用rails' ActiveRecord接口获取记录,但它证明有点困难。这是问题所在:

3个表:事物,用户,协作

3个连接表:things_users,collaborations_things,collaboration_users

我试图获取内容(使用伪SQL,跳过JOINS)

things WHERE
things.criteria = something OR
user_id IN things_users.user_id OR
user_id IN users_collaboration.user_id

值得注意的是,事情可能没有用户或协作,因此需要外部联接。

模特:

class User < ActiveRecord::Base
  // Unrelated stuff
  has_and_belongs_to_many :collaborations
end

class Thing < ActiveRecord::Base
    // Unrelated
    has_and_belongs_to_many :users
    has_and_belongs_to_many :collaborations
end

class Collaboration < ActiveRecord::Base
  has_and_belongs_to_many :members, :join_table => 'collaborations_users', :association_foreign_key => 'user_id'
end

我尝试使用直接界面,​​arel和直接SQL,但出于某种原因,我无法找到正确的魔法来使它全部工作。

如果有人可以提供帮助,那就太棒了。 感谢

1 个答案:

答案 0 :(得分:0)

可能看起来像这样的SQL(适当地替换&lt;&gt;部分):

SELECT t.* 
FROM things t
LEFT OUTER JOIN things_users tu ON t.id = tu.thing_id
LEFT OUTER JOIN collaborations_things ct ON t.id = ct.thing_id
LEFT OUTER JOIN collaborations_users cu ON ct.collaboration_id = cu.collaboration_id
WHERE <things table criteria> OR tu.user_id = <user_id> OR cu.user_id = <user_id>

要使用ActiveRecord,您可以使用:

Thing.joins("LEFT JOIN things_users ON things.id = things_users.thing_id LEFT JOIN collaborations_things ON thing.id = collaborations_things.thing_id LEFT JOIN collaborations_users ON collaborations_things.collaboration_id = collaborations_users.collaboration_id").where(["<other criteria> OR things_users.user_id = :user_id OR collaborations_users = :user_id", {user_id: @user_id}]