Help us understand the problem. What is going on with this article?

Ruby on Rails + MySQLデータ挿入

More than 1 year has passed since last update.

環境

  • 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)

データ挿入

INSERT

user = User.new(uuid: 'ABCDEFG',name: 'newUser', age: 99)
user.save

もしくは

user = User.create(uuid: 'ABCDEFG',name: 'newUser', age: 99)

createはnewとsaveを同時に行ってくれる。便利!!

でも、saveを使うとinsert処理の成功・失敗が返ってくるので処理の成否でその後の処理を分けたい場合はsaveを使うべき。

BULK INSERT

*BULK INSERTそのものについてはこちらを参考
バルクインサート (bulk insert)とは

activerecord-importを使用します。

Gemfileに

gem 'activerecord-import'

を追記し、 bundle installします。

bundle installしたら下記のような処理を書くことによってbulk insertが使用できます。

newUsers = []
newUsers << User.new(uuid: 'AAA', name: 'AAAname', age: 90)
newUsers << User.new(uuid: 'BBB', name: 'BBBname', age: 80)
newUsers << User.new(uuid: 'CCC', name: 'CCCname', age: 70)
User.import newUsers

実際に実行されたSQLが↓です

INSERT INTO `users` (`id`,`uuid`,`name`,`age`,`created_at`,`updated_at`) 
VALUES (NULL,'AAA','AAAname',90,'2017-10-09 05:11:12','2017-10-09 05:11:12'),
(NULL,'BBB','BBBname',80,'2017-10-09 05:11:12','2017-10-09 05:11:12'),
(NULL,'CCC','CCCname',70,'2017-10-09 05:11:12','2017-10-09 05:11:12')
ON DUPLICATE KEY UPDATE `users`.`updated_at`=VALUES(`updated_at`)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away