是否可以在Rails 4中向LEFT OUTER JOIN添加条件?

时间:2015-03-11 02:09:53

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

鉴于这种结构:

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

目标是获取帐户的所有团队ID /名称的列表/数组,以及指示给定用户是否属于团队的标志。

在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 = ?

是否有Rails 4 / ActiveRecord方式来获得相同的结果?我所做的每一次尝试都将teams_users.user_id = ?条件推送到WHERE子句中,该子句仅返回用户所属的团队列表,而不是与该帐户关联的所有团队。

1 个答案:

答案 0 :(得分:3)

应该可以使用joins的字符串形式。在插入字符串之前清理任何用户输入。

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)