1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Active Record】ヒアドキュメントを活用して条件付LEFT JOINを行う

Last updated at Posted at 2020-11-13

テーブル

notes

id title body
1 おはよう おはおはおはおは
2 こんにちは こんこんこんこん
3 こんばんは こんこんこんこん

likes

id note_id user_id
1 1 1
2 2 2
3 2 2
4 3 3

やりたいこと

「notesの全レコードと、noetsに結合したlikesレコード(user_id = 1)の情報を取得」

結論

sample.rb
# user.id = 1
user = User.find_by(email: "test@gmail.com")
Note.joins(
      <<~SQL
        LEFT OUTER JOIN `likes` ON `likes`.`note_id` = `notes`.`id`\
        AND `likes`.`user_id` = #{user.id}
      SQL
     )

取得結果

id title body id note_id user_id
1 おはよう おはおはおはおは 1 1 1
2 こんにちは こんこんこんこん
3 こんばんは こんこんこんこん
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?