[RUBY] [Rails] Create initial data with seed.rb [Faker] [Japanese localization]

Introduction

--My specs --Rails learning history: 4 months --Conditions

Therefore, there may be mistakes, so ** Don't swallow! **

install gem "Faker"

  1. Add gem'faker to Gemfile
  2. Run bundle install on the terminal

Gemfile


gem 'faker'

Terminal


$ bundle install

Japaneseize "Faker"

--Japaneseize the entire Rails ** OR ** Japaneseize only Faker

config/initializers/locale.rb


Rails.application.config.i18n.default_locale = :ja ##When translating the entire Rail into Japanese
Faker::Config.locale = :ja ##When only Faker is translated into Japanese
##You can translate it into Japanese by setting only one of them.

References Faker's Github Faker usage example (English)

Customize the Japanese translation of "Faker"

  1. Download ja.yml from Github
  2. Place ja.yml in config/locales/faker
  3. Make config.i18n.load_path load any directory under config/locales
  4. Customize the downloaded ja.yml to your liking

Terminal


##wget [URL of the file you want to download]-P [Location where you want to store downloaded files]
$ wget https://raw.githubusercontent.com/faker-ruby/faker/master/lib/locales/ja.yml -P config/locales/faker

config/application.rb


module Club
  class Application < Rails::Application
    ...
    config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}').to_s]
    ...
  end
end

Input demo data with seed.rb

As a prerequisite, the initial data is input to the User model, Group model and its two intermediate tables GroupUser model.

  1. Decide the number of demo data to be created by default.
  2. Input the data used by the test user in the test data.
  3. Create users and groups.
  4. Make users join the group with a 1/5 chance of randomness.
  5. Reset the DB with rails db: migrate: reset and fill the initial data with rails db: seed.

db/seeds.rb


#Initial setting
users_number = 20
groups_number = 20

#test data
User.create!(name: 'Takashi Sato',
              email: '[email protected]',
              password: 'password',
              description: 'Nice to meet you everyone! !! !!')

Group.create!(name: 'swimming',
              description: 'We are working hard every day to win the prefecture.')

GroupUser.create!(group_id: 1,
                  user_id: 1)

#user
users_list = []
users_number.times do
  users_list << {name: Faker::Name.unique.name,
                email:  Faker::Internet.unique.email,
                password: 'password',
                description: 'nice to meet you!'}
end
User.create!(users_list)

#group
groups_list = []
groups_number.times do
  groups_list << {name: Faker::Team.unique.sport,
                description: 'Please join us! !!'}
end
Group.create!(groups_list)

# 1/5 chances to join one group
group_users_list = []
User.all.ids.each do |user_id|
  Group.all.ids.each do |group_id|
    if rand(5) == 0 && (user_id != 1 && group_id != 1)
      group_users_list << { user_id: user_id, group_id: group_id}
    end
  end
end
GroupUser.create!(group_users_list)

Terminal


$ rails db:migrate:reset
$ rails db:seed

Create multiple data at once using an array

  1. Store the user to be created this time with users_list. (I won't use it this time, but it may be useful later)
  2. Create users a specified number of times using users_number.times.
  3. Store the information of one user in users_list in one block process.
  4. Use User.create! (Users_list) to create all the users stored in users_list.

python



users_list = []
users_number.times do
  users_list << {name: Faker::Name.unique.name,
                email:  Faker::Internet.unique.email,
                password: 'password',
                description: 'nice to meet you!'}
end
User.create!(users_list)

References Use create and create! properly

Create data irregularly using rand ()

It's a hassle to decide who will join which group, so we'll use rand () to simplify it.

  1. Get the IDs of all users and groups with User.all.ids.each and Group.all.ids.each.
  2. Execute with if rand (5) == 0 with a probability of 1/5. (* Rand (5) outputs numbers from 0 to 4 at random.)
  3. (user_id! = 1 && group_id! = 1) is registered as test data above, so exclude it so that it is not duplicated.
  4. Use GroupUser.create! (Group_users_list) to create all the data stored in group_users_list.

python


group_users_list = []
User.all.ids.each do |user_id|
  Group.all.ids.each do |group_id|
    if rand(5) == 0 && (user_id != 1 && group_id != 1)
      group_users_list << { user_id: user_id, group_id: group_id}
    end
  end
end
GroupUser.create!(group_users_list)

References [Introduction to Ruby] Mastering random![Numeric value, character string, array, secure] [Application of Ruby each] Let's comprehensively understand various usages [Rails] I made the initial data of the association

Recommended Posts

[Rails] Create initial data with seed.rb [Faker] [Japanese localization]
[Rails] Initial data creation with seed
Initial data input with [Rails] seed_fu!
Create realistic dummy data with gem Faker
Create dummy data of portfolio with Faker [Note]
Create an EC site with Rails5 ⑥ ~ seed data input ~
[Rails] Japanese localization using rails-i18n
[Rails] Japanese localization of error messages
Create portfolio with rails + postgres sql
[Rails] Validation settings and Japanese localization
Create My Page with Rails devise
[Ruby on Rails] Introduction of initial data
[Rails6] Create a new app with Rails [Beginner]
Create Rails 6 + MySQL environment with Docker compose
[Rails withdrawal] Create a simple withdrawal function with rails
[Rails 5] Create a new app with Rails [Beginner]
Script to make yaml from CSV to put initial data in Rails with Fixtures
[Rails] rails new to create a database with PostgreSQL
Rails: Japanese localization of validation messages including devise
[Japanese localization] i18n rails Easy Japanese localization view display only
Create related data together with FactoryBot for yourself
Launch Docker image with initial data injected with docker-compose
Create an EC site with Rails5 ⑤ ~ Customer model ~
Create an EC site with Rails 5 ⑩ ~ Create an order function ~