如何使外部连接脱离条件

时间:2018-07-13 07:50:21

标签: ruby-on-rails join

我有这种关系:

class Action < ApplicationRecord
   has_many :actions_users

我试图进行如下查询:

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions.user_id = 1

同时,根据我的经验,我尝试的所有结果,

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id
where actions.user_id = 1 and actions_users.user_id = 1 

加入条件代码和一般条件在where函数中。

我该如何解决?

3 个答案:

答案 0 :(得分:0)

您可以在联接查询中传递字符串,并为此使用rails表命名约定。

Action.joins("left outer join action_users on (action_users.id = actions.id and action_users.id = 1")).where('action_users.user_id = ? ', 1)

答案 1 :(得分:0)

因为您有一般的where条件,所以可以使用includes。这将生成一个LEFT OUTER JOIN查询:

Action.includes(:actions_users).where(actions_users: { user_id: true })

或者,如果您使用的是Rails 5+,则Active Record提供了一种查找器方法left_outer_joins

Action.left_outer_joins(:actions_users).where(actions_users: { user_id: true })

答案 2 :(得分:0)

Action.left_outer_joins(:actions_users).where(user_id: 1)

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions.user_id = 1

尽管您还没有要求,...

Action.left_outer_joins(:actions_users).where(actions_users: {status: 'active'})

select *
from actions left outer join actions_users
on actions_users.action_id = actions.id and actions_users.user_id = 1
where actions_users.status = 'active'