1
1

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 1 year has passed since last update.

to_sqlメソッドでActiveRecord実行時のSQLを確認

Last updated at Posted at 2022-10-01

1. to_sqlを使用し、ActiveRecordのクエリを出力

sample.rb
target_members = Member.joins(:positions).where(positions: { position_status: 5 })
puts target_members.to_sql
  • RSpecで任意のテストを実行すると、putsメソッドを使っているため標準出力に出力される
Run
SELECT "members".* FROM "members" INNER JOIN "positions" ON "positions"."member_id" = "members"."id" WHERE "positions"."position_status" = 5

pメソッドで出力している際は出力結果に"(ダブルクォーテーション)のみならず\(バックスラッシュ)も含まれる

2. エディタなどで置換

  • 私はいつもVisual Studio Codeで整えています
    • 任意のファイルに出力された結果を貼り付ける
    • command + f
    • "(ダブルクォーテーション)を全て置換し削除
      スクリーンショット 2022-10-01 19.42.00.png
整形後
SELECT members.* FROM members INNER JOIN positions ON positions.member_id = members.id WHERE positions.position_status = 5

3. SQL整形ツールを使用

  • 貼り付けて「整形する」ボタンを押下するだけでOK
SQL
SELECT
    members.*
FROM
    members
    INNER JOIN
        positions
    ON  positions.member_id = members.id
WHERE
    positions.position_status = 5
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?