🌊

【Rails】Active Recordでどんなクエリが発行されているのか見てみる。

2 min read

メモリたいものが増えたら更新する。

all

Rails
User.all
SQL
SELECT "users".* FROM "users"

select

Rails
User.select(:name)
SQL
SELECT "name" FROM "users" LIMIT $1  [["LIMIT", 11]]

find

Rails
User.find(1)
SQL
SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]

find_by

Rails
User.find_by(email: 'hoge@hoge')
SQL
SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "hoge@hoge"], ["LIMIT", 1]]

where

Rails
User.where(email: 'hoge@hoge')
SQL
SELECT "users".* FROM "users" WHERE "users"."email" = $1  [["email", "hoge@hoge"]]

create

Rails
User.create(email: 'fuga@fuga', password: 'fuga', password_confirmation: 'fuga', family_name: 'fuga', given_name: 'fuga')

※User.emailにはユニーク縛りあり。

SQL
SELECT 1 AS one FROM "users" WHERE "users"."email" = $1 LIMIT $2  [["email", "fuga@fuga"], ["LIMIT", 1]]
INSERT INTO "users" ("email", "password_digest", "created_at", "updated_at", "family_name", "given_name") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"  [["email", "fuga@fuga"], ["password_digest", "○○"], ["created_at", "2021-01-17 06:08:37.410580"], ["updated_at", "2021-01-17 06:08:37.410580"], ["family_name", "fuga"], ["given_name", "fuga"]]

group

Rails
Address.group(:user_id)
SQL
SELECT "addresses".* FROM "addresses" GROUP BY "addresses"."postal_code"

having

Rails
Address.group(:user_id).having('count(*) > ?', 2).count
SQL
SELECT "addresses".* FROM "addresses" GROUP BY "addresses"."user_id" HAVING (count(*) > 2)

関連付け(association)

Rails
User.find(1).addresses
SQL
SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id" = $1  [["user_id", 1]]
Rails
Address.find(1).user
SQL
SELECT "addresses".* FROM "addresses" WHERE "addresses"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
Rails
User.includes('addresses').all
SQL
SELECT "users".* FROM "users"
SELECT "addresses".* FROM "addresses" WHERE "addresses"."user_id" = $1  [["user_id", 1]]

join(内部結合)

Rails
User.joins(:addresses)
SQL
SELECT "users".* FROM "users" INNER JOIN "addresses" ON "addresses"."user_id" = "users"."id"

left_joins(左外部結合)

Rails
User.left_joins(:addresses)
SQL
SELECT "users".* FROM "users" LEFT OUTER JOIN "addresses" ON "addresses"."user_id" = "users"."id"

Discussion

ログインするとコメントできます