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.

【Rails】Active Recordのメソッドまとめ

Posted at

概要

RailsのActiveRecordのメソッドの違いがよくわからなくなるため、
Railsチュートリアルの第6章をもとに、備忘としてまとめ。

環境

ruby 3.0.2
rails 6.1.4
mysql 8.0.26

例とするUserモデルの定義

カラム データ型
id integer
name string
email string
created_at datetime
updated_at datetime

機能(CRUD:SQL)

作成(Create:INSERT)

  • new
console
# 【モデルの生成】メモリ上でオブジェクトを作成
>> user1 = User.new(name: "hoge1", email: "hoge1@gmail.com")
=> 
#<User:0x00007fd6144a3390
...
>> user1
=> 
#<User:0x00007fd6144a3390
 id: nil,
 name: "hoge1",
 email: "hoge1@gmail.com",
 created_at: nil,
 updated_at: nil>
  • save
console
# 【モデルの保存】データベースにオブジェクトを保存
>> user1.save
  TRANSACTION (0.6ms)  SAVEPOINT active_record_1
  User Create (0.4ms)  INSERT INTO `users` (`name`, `email`, `created_at`, `updated_at`) VALUES ('hoge', 'hoge@gmail.com', '2021-12-12 12:21:19.152562', '2021-12-12 12:21:19.152562')
  TRANSACTION (0.6ms)  RELEASE SAVEPOINT active_record_1
=> true

  • newだけでは、データベースまでは保存されない

  • saveを実行して初めて、データベースへINSERTされる

  • save実行のタイミングで、id属性、created_at属性、updated_at属性に値が入る

  • saveの返り値:成功→true 失敗→false

  • create

console
# 【モデルの生成】オブジェクトを作成し、データベースに保存
>> user2 = User.create(name:"hoge2",email:"hoge2@gmail.com" )
  TRANSACTION (1.4ms)  SAVEPOINT active_record_1
  User Create (3.0ms)  INSERT INTO `users` (`name`, `email`, `created_at`, `updated_at`) VALUES ('hoge2', 'hoge2@gmail.com', '2021-12-12 12:30:06.108801', '2021-12-12 12:30:06.108801')
  TRANSACTION (1.1ms)  RELEASE SAVEPOINT active_record_1
=> 
#<User:0x00007fd61026c968
...
  • newとsaveを同時に実行
  • 返り値:ユーザーオブジェクト自身

読み出し(Read:SELECT)

  • all
console
>> User.all
  User Load (1.5ms)  SELECT `users`.* FROM `users`
=> 
[#<User:0x00007fd6179713b0
  id: 1,
  name: "hoge1",
  email: "hoge1@gmail.com",
  created_at: Sun, 12 Dec 2021 11:20:00.811897000 UTC +00:00,
  updated_at: Sun, 12 Dec 2021 11:21:43.909826000 UTC +00:00>,
 #<User:0x00007fd6179712e8
  id: 2,
  name: "hoge2",
  email: "hoge2@gmail.com",
  created_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00,
  updated_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00>]

  • データベースの全てのUserオブジェクトを返す

  • find

console
# 【idで検索】
>> User.find(1)
  User Load (0.7ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
=> 
#<User:0x00007fd61692a6f0
 id: 1,
 name: "hoge1",
 email: "hoge1@gmail.com",
 created_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00,
 updated_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00>
  • findにidを渡すと、そのidのユーザーを返す

  • find_by

console
# 【id以外の属性を指定して検索】
>> User.find_by(email:"hoge1@gmail.com")
  User Load (1.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`email` = 'hoge1@gmail.com' LIMIT 1
=> 
#<User:0x00007fd6178bcc80
 id: 1,
 name: "hoge1",
 email: "hoge1@gmail.com",
 created_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00,
 updated_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00>
  • 任意の属性を指定して検索が可能

  • first

console
>> User.first
  User Load (0.5ms)  SELECT `users`.* FROM `users` ORDER BY `users`.`id` ASC LIMIT 1
=> 
#<User:0x00007fd611398688
 id: 1,
 name: "hoge1",
 email: "hoge1@gmail.com",
 created_at: Sun, 12 Dec 2021 11:20:00.811897000 UTC +00:00,
 updated_at: Sun, 12 Dec 2021 11:21:43.909826000 UTC +00:00>
  • データベースの最初のユーザーを返す

削除(Delete:DELETE)

  • destroy
console
>> user2.destroy
  TRANSACTION (0.4ms)  SAVEPOINT active_record_1
  User Destroy (0.5ms)  DELETE FROM `users` WHERE `users`.`id` = 2
  TRANSACTION (0.6ms)  RELEASE SAVEPOINT active_record_1
=> 
#<User:0x00007fd61026c968
 id: 2,
 name: "hoge2",
 email: "hoge2@gmail.com",
 created_at: Sun, 12 Dec 2021 12:30:06.108801000 UTC +00:00,
 updated_at: Sun, 12 Dec 2021 12:30:06.108801000 UTC +00:00>
>> 
  • 削除されたオブジェクトは、メモリ上には残っている

更新(Update:UPDATE)

  • 個別に代入→save
console
# 既存の値を確認
>> user1.email
=> "hoge1@gmail.com"
# 新しい値を代入
>> user1.email = "hoge3@gmail.com"
=> "hoge3@gmail.com"
# オブジェクト上での更新を確認
>> user1.email
=> "hoge3@gmail.com"
# データベースに変更を保存
>> user1.save
  TRANSACTION (0.4ms)  SAVEPOINT active_record_1
  User Update (0.5ms)  UPDATE `users` SET `users`.`email` = 'hoge3@gmail.com', `users`.`updated_at` = '2021-12-12 12:48:53.820375' WHERE `users`.`id` = 1
  TRANSACTION (0.7ms)  RELEASE SAVEPOINT active_record_1
=> true
  • reloadメソッドが実行されると、データベースの情報をもとにオブジェクトを再読み込みするため、変更が取り消される

  • 変更を保存する場合は、saveを実行する

  • update

console
# 既存の値を確認
>> user1
=> 
#<User:0x00007fd6144a3390
 id: 1,
 name: "hoge1",
 email: "hoge3@gmail.com",
 created_at: Sun, 12 Dec 2021 12:21:19.152562000 UTC +00:00,
 updated_at: Sun, 12 Dec 2021 12:52:29.039633000 UTC +00:00>
# update実行
>> user1.update(name: "hoge4", email: "hoge4@gmail.com")
  TRANSACTION (0.6ms)  SAVEPOINT active_record_1
  User Update (1.0ms)  UPDATE `users` SET `users`.`name` = 'hoge4', `users`.`email` = 'hoge4@gmail.com', `users`.`updated_at` = '2021-12-12 12:54:24.491310' WHERE `users`.`id` = 1
  TRANSACTION (0.8ms)  RELEASE SAVEPOINT active_record_1
=> true
  • 成功時には更新と保存を続けて同時に行う

  • 保存に成功した場合はtrueを返す

  • 検証に1つでも失敗すると、updateの呼び出しは失敗する

  • update_attribute

console
#【nameのみ更新】
>> user1.update_attribute(:name, "hoge5")
  TRANSACTION (0.4ms)  SAVEPOINT active_record_1
  User Update (1.0ms)  UPDATE `users` SET `users`.`name` = 'hoge5', `users`.`updated_at` = '2021-12-12 12:57:33.541181' WHERE `users`.`id` = 1
  TRANSACTION (0.8ms)  RELEASE SAVEPOINT active_record_1
=> true
  • 特定の属性のみを更新可能
  • 検証を回避することができる

最後に

その他のメソッドや細かい仕様については追々まとめていきたい。

※間違い等ありましたらご指摘いただけますと幸いです!

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?