[英]Is it possible to add a condition to a LEFT OUTER JOIN in Rails 4?
Given this structure: 鉴于此结构:
class Account < ActiveRecord::Base
has_many :users
has_many :teams
validates :name, presence: true
end
class User < ActiveRecord::Base
belongs_to :account
has_and_belongs_to_many :teams
validates :name, presence: true
end
class Team < ActiveRecord::Base
belongs_to :account
has_and_belongs_to_many :users
validates :name, presence: true
end
The objective is to obtain a list/array of all the team ids/names for an account, along with a flag indicating whether a given user belongs to the team or not. 目的是获得帐户的所有团队ID /名称的列表/数组,以及指示给定用户是否属于团队的标志。
In SQL I can get this result with something like: 在SQL中,我可以通过以下方式获得此结果:
SELECT teams.id, teams.name,
teams_users.team_id IS NOT NULL AS member FROM teams
LEFT OUTER JOIN teams_users ON
(teams.id = teams_users.team_id AND team_users.user_id = ?)
WHERE teams.account_id = ?
Is there a Rails 4 / ActiveRecord way to get the same result? 是否有Rails 4 / ActiveRecord方式来获得相同的结果? Every attempt I've made has pushed the
teams_users.user_id = ?
我所做的每一次尝试都将
teams_users.user_id = ?
condition into the WHERE clause, which only returns a list of teams for which the user is a member, rather than all the teams associated with the account. 条件到WHERE子句中,该子句仅返回用户是其成员的团队的列表,而不是与该帐户关联的所有团队的列表。
It should be possible with the string form of joins
. 字符串形式的
joins
应该是可能的。 Sanitize any user input before interpolating into the string. 插值到字符串之前,请先清理所有用户输入。
Team.select(:id, :name).
select("teams_users.team_id IS NOT NULL AS member FROM teams").
joins("LEFT OUTER JOIN teams_users ON (teams.id = teams_users.team_id AND team_users.user_id = #{current_user.id})").
where(account_id: account.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.