具有多个OR子查询的Rails Arel

时间:2018-12-21 17:53:48

标签: ruby-on-rails activerecord arel

我当前的ActiveRecord查询如下:

    team_query = <<-TEAMQUERY
( ( tasks.taskable_type = 'Account'
       AND tasks.taskable_id IN (SELECT id
                                 FROM   accounts
                                 WHERE  accounts.team_id = :team_id) )
      OR ( tasks.taskable_type = 'Business'
           AND tasks.taskable_id IN (SELECT id
                                     FROM   businesses
                                     WHERE  businesses.team_id = :team_id) )
      OR ( tasks.taskable_type = 'Team'
           AND tasks.taskable_id = :team_id ) )
TEAMQUERY

Task.where(team_query, team_id: team_id).count

基本上,我需要团队ID,但也要使用它来检查帐户/业务。

我正在尝试使用AREL进行重写,但目前无法产生正确的输出

t = Task.arel_table
team_query = t[:taskable_type].eq('Team').and(t[:taskable_id].eq(team_id))

a = Account.arel_table
account_query = t[:taskable_type].eq('Account').and(t[:taskable_id].in(a.project(a[:id]).where(a[:team_id].eq(team_id))))

b = Business.arel_table
business_query = t[:taskable_type].eq('Business').and(t[:taskable_id].in(b.project(b[:id]).where(b[:team_id].eq(team_id))))

Task.where(team_query.or(account_query).or(business_query)).count

0 个答案:

没有答案