如何在同一个表中的两列上执行OR?

时间:2015-11-04 20:59:13

标签: ruby-on-rails-4 activerecord

我有membership模型,我想在两列上搜索OR ....不知道该怎么做。

我试过了:

u1.all_memberships.where(inviter: u2, invited: u2)
  Membership Load (6.8ms)  SELECT "memberships".* FROM "memberships"  WHERE (memberships.user_id = 1 OR memberships.invited_id = 1) AND "memberships"."user_id" = 3 AND "memberships"."invited_id" = 3
=> []

但请注意两个查询中的AND,理想情况下,我想要做的只是用AND替换所有OR s。

如果查询看起来像这样,我会很高兴:

Membership Load (6.8ms)  SELECT "memberships".* FROM "memberships"  WHERE (memberships.user_id = 1 OR memberships.invited_id = 1) OR (memberships.user_id = 3 OR memberships.invited_id = 3)

假设我的修改在语法上是正确的SQL ofcourse。

如何使用where子句执行此操作?这可能吗?

1 个答案:

答案 0 :(得分:2)

我希望它可以提供帮助

where("inviter_id = ? OR invited_id = ? ", u2.id, u2.id)

DRYer解决方案

where("inviter_id = :uid OR invited_id = :uid ", uid: u2.id)