[Rails] I want to write compactly by creating seed (% w notation, each_with_index, numbering parameter)

In seed registration, I tried to summarize various things using ruby ​​notation etc.

Basic

User.create!(name: 'Tanaka', email: '[email protected]')
User.create!(name: 'Suzuki', email: '[email protected]')

Two-dimensional array

array = [ ['Tanaka', '[email protected]'], ['Suzuki', '[email protected]'] ]
array.each do |first, second|
  User.create!(name: first, email: second)
end

Two-dimensional array (compact)

[
  ['Tanaka', '[email protected]'], ['Suzuki', '[email protected]']
].each do |first, second|
  User.create!(name: first, email: second)
end

% w notation

array = %w[Tanaka [email protected]], %w[Suzuki [email protected]]
array.each do |first, second|
  User.create!(name: first, email: second)
end

% w notation (compact)

[
  %w[Tanaka [email protected] tokyo\I'm from Hachioji],
  %w[Suzuki [email protected] Okinawa\I'm from Naha city]
].each do |first, second, third|
  User.create!(name: first, email: second, birthplace: third)
end

each_with_index You don't have to write i = 1, i + = 1 or increment processing. Make index easier to handle.

array = [ ['Tanaka', 'Suzuki'] ]
array.each_with_index do |first, i|
  User.create!(name: first, index_no: i)
end

each.with_index(n) Specify the start number.

[
  ['Tanaka', 'Suzuki']
].each.with_index(5) do |first, i|
  User.create!(name: first, index_no: i)
end

each_with_index (for 2D arrays)

[
  ['Tanaka', '[email protected]'], ['Suzuki', '[email protected]']
].each_with_index do |(first, second), i|
  User.create!(name: first, email: second, index_no: i)
end

Numbering parameter

do |first, second|Is no longer necessary.

[
  ['Tanaka', '[email protected]'], ['Suzuki', '[email protected]']
].each do
  User.create!(name: _1, email: _2)
end

Finally

Let's run rails db: seed to reflect the data.

I hope it helps someone.

Referenced materials

**% notation ** https://qiita.com/mogulla3/items/46bb876391be07921743 https://www.sejuku.net/blog/46939 each_with_index http://blog59.hatenablog.com/entry/2018/02/28/155417 ** Insert an empty string in% notation ** https://qiita.com/nao58/items/d897c16c9513dcf54ade ** Numbering parameters ** https://qiita.com/jnchito/items/79f0172e60f237e2c542

Recommended Posts

[Rails] I want to write compactly by creating seed (% w notation, each_with_index, numbering parameter)
How to write Rails seed
I want to write a nice build.gradle
I want to write a unit test!
I want to sort by tab delimited by ruby
[Rails] Various ways to write in seed files
I want to use arrow notation in Ruby
I want to simply write a repeating string
I want to play with Firestore from Rails
I want to write quickly from java to sqlite
[Rails] I want to load CSS with webpacker
I want to delete files managed by Git
I want to use a little icon in Rails
I want to authenticate users to Rails with Devise + OmniAuth
I want to define a function in Rails Console