0
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.

find, find_by, where使い方[Active Record]

Last updated at Posted at 2021-04-01

#allメソッド
モデルの全件のレコードを返します。

 Post.all

 #SQL
 SELECT  "posts".* FROM "posts"

#findメソッド
主キー(id)を指定して、見つかった1レコードを返します。

 Post.find(1)
 #id: 1のレコードを返す

# SQL
SELECT  "posts".* FROM "posts" 
WHERE "posts"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]

#find_byメソッド

主キー(id)以外のカラムを指定しても、見つかった1レコードを返します。

 Post.find_by(title: "closet")
 #titleが"closet"のレコードを返す


#SQL
SELECT  "posts".* FROM "posts" 
WHERE "posts"."title" = ? LIMIT ?  [["title", "closet"], ["LIMIT", 1]]

#whereメソッド

 Post.where(title: "closet")
 #titleが"closet"のレコードを全て返す

#SQL
SELECT  "posts".* FROM "posts" 
WHERE "posts"."title" = ? LIMIT ?  [["title", "closet"], ["LIMIT", 11]]

#find_or_create_by

User.find_or_create_by(email: 'hoge@example.com')
#'User'の中から'email'が'hoge@example.com'のレコードが無かったら作成してくれます。

#SQL
SELECT * FROM users WHERE (users.email = 'hoge@example.com') LIMIT 1
BEGIN
INSERT INTO users (created_at, email, locked, orders_count, updated_at) 
VALUES ('2021-04-01 05:55:55', 'hoge@example.com', 1, NULL, '2021-04-01 05:55:55')
COMMIT

#takeメソッド

 Post.take(10)
 #10件データ取って来て返す
 #ただし、レコードの指定ができない

#SQL
SELECT * FROM "posts" LIMIT 10

#firstメソッド

 Post.first
 #主キー順の最初のレコードを取ってくる

#SQL
ELECT * FROM posts ORDER BY posts.id ASC LIMIT 1

#lastメソッド

 Post.last
 #主キー順の最後のレコードを取ってくる

#SQL
SELECT * FROM posts ORDER BY posts.id DESC LIMIT 1

#参考
Railsガイド6.1

0
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
0
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?