seed登録にて、rubyの記法など使ったものを色々まとめてみました。
基本
User.create!(name: '田中', email: 'tanaka@test.com')
User.create!(name: '鈴木', email: 'suzuki@test.com')
二次元配列
array = [ ['田中', 'tanaka@test.com'], ['鈴木', 'suzuki@test.com'] ]
array.each do |first, second|
User.create!(name: first, email: second)
end
二次元配列(コンパクトに)
[
['田中', 'tanaka@test.com'], ['鈴木', 'suzuki@test.com']
].each do |first, second|
User.create!(name: first, email: second)
end
%w記法
array = %w[田中 tanaka@test.com], %w[鈴木 suzuki@test.com]
array.each do |first, second|
User.create!(name: first, email: second)
end
%w記法(コンパクトに)
※空文字を使う場合(バクスラ+半角スペ)
[
%w[田中 tanaka@test.com 東京都\ 出身は八王子市です],
%w[鈴木 suzuki@test.com 沖縄県\ 出身は那覇市です]
].each do |first, second, third|
User.create!(name: first, email: second, birthplace: third)
end
each_with_index
i=1, i+=1 とかインクリメント処理を書かなくていい。indexを扱いやすくする。
※i=0から始まる。
array = [ ['田中', '鈴木'] ]
array.each_with_index do |first, i|
User.create!(name: first, index_no: i)
end
each.with_index(n)
開始番号を指定する。
[
['田中', '鈴木']
].each.with_index(5) do |first, i|
User.create!(name: first, index_no: i)
end
each_with_index(二次元配列の場合)
[
['田中', 'tanaka@test.com'], ['鈴木', 'suzuki@test.com']
].each_with_index do |(first, second), i|
User.create!(name: first, email: second, index_no: i)
end
番号指定パラメータ
do |first, second|といった記載が不要になります。
※注意:_1〜_9まで使用でき_10は使用不可です。
[
['田中', 'tanaka@test.com'], ['鈴木', 'suzuki@test.com']
].each do
User.create!(name: _1, email: _2)
end
最後に
rails db:seed
を実行してデータを反映しましょう。
どなたかのお役に立てれば幸いです。
参考にした資料
%記法いろいろ
https://qiita.com/mogulla3/items/46bb876391be07921743
https://www.sejuku.net/blog/46939
each_with_index
http://blog59.hatenablog.com/entry/2018/02/28/155417
%記法で空文字を入れる
https://qiita.com/nao58/items/d897c16c9513dcf54ade
番号指定パラメータ
https://qiita.com/jnchito/items/79f0172e60f237e2c542