33
23

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 5 years have passed since last update.

Ruby on Rails データ更新

Posted at

環境

  • CentOS6.5
  • Rails 5.1.4
  • MySQL 5.7
  • Ruby 2.3.1

RailsでMySQLのテーブル作成で作成したテーブルを使います。

テーブル名:

  • users

カラム:

  • id (BIGINT(20)) <= PK
  • uuid (varchar(255))
  • name (varchar(255))
  • age (int(11))
  • created_at (datetime)
  • updated_at (datetime)

基本

ID3のユーザのageを50に更新します。

user = User.find(3)
user.age = 50
user.save

↓ が実行される

SELECT  `users`.* FROM `users` WHERE `users`.`id` = 3 LIMIT 1
UPDATE `users` SET `age` = 50, `updated_at` = '2017-10-09 05:49:44' WHERE `users`.`id` = 3

複数レコードの場合はどうなるか??

全てのレコード更新

usersテーブルの全てのレコードのageを1000にします

User.update_all ['age = ?', 1000]

これが実行される

UPDATE `users` SET age = 1000

条件に当てはまる複数レコードを更新

例:age = 2のデータのnameをZZZにしたい

イメージ:

UPDATE users SET name = 'ZZZ' WHERE age = 2

をRailsで実行できるようにしたい。

users = User.where('age = ?', 2).update_all(:name => 'ZZZ')

イメージ通り、↓が実行された!

UPDATE `users` SET `users`.`name` = 'ZZZ' WHERE (age = 2)
33
23
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
33
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?