LoginSignup
1
0

More than 1 year has passed since last update.

RailsでON句を綺麗に書きたい

Last updated at Posted at 2021-11-19

目的

ActiveRecordで、(WHERE句でなく)ON句で絞り込んでからテーブルをJOINしたいが、ON句用のメソッドがない。
できるだけActiveRecordっぽく、綺麗に書きたい。

結論

テーブルをJOINする.join()の直後に、.join("AND ...")でON句は直書きする。

Sample.joins(:users) # usersテーブルをJOIN
      .joins("AND users.type = #{User::USERTYPE_COOK}") # 調理師(ON句)
      .where(users: {id: params[:user_id]} )
SELECT `samples`.* 
FROM `samples` 
INNER JOIN `users` 
  ON `users`.`id` = `samples`.`user_id`
  AND users.type = "cook"
WHERE `users`.`id` = 1
;

備考

.merge()を試したがダメだった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0