[RUBY] # 8 seed implementation to build bulletin board API with authentication authorization in Rails 6

Building a bulletin board API with authentication authorization with Rails 6 # 7 update, destroy implementation

What is seed

Whenever test data is needed during development, it is troublesome to hit rails c or create action to create a record. Therefore, we will introduce a seed that makes it easy to create a preset record, 50 or 1000, just by hitting a command.

File creation and loading

If you google only rails seed, it will usually be written directly in db / seeds.rb, but if there are many models, it will be difficult to manage. Therefore, divide the file and make it a format called by require from db / seeds.rb.

This makes it easier to manage when adding or deleting, and seed can also be executed by specifying a file, which is convenient.

$ mkdir db/seeds
$ touch db/seeds/post_seeds.rb

db/seeds.rb


# frozen_string_literal: true

seed_models = %i[post]
seed_models.each do |model|
  require "./db/seeds/#{model}_seeds"
end

db/seeds/post_seeds.rb


# frozen_string_literal: true

unless Post.exists?
  20.times do
    Post.create!(subject: "hoge", body: "fuga")
  end
end

Expecting that the number of models to be seeded will increase in the future, we will read the external file by adding it to the variable called seed_models. By scanning the directory, you can make it so that you do not have to change db / seeds.rb each time, but there will be dependencies such as the user model record to be created in the future must exist before the post model. So, I wrote it so that I can manually play with the execution order.

The contents of post_seeds.rb are simply running Post.create! 20 times. By adding !, An exception will be thrown when registration cannot be performed due to a validation error, so if you notice it, you can prevent the situation where the record was not generated.

$ rails db:reset
$ rails db:seed
$ rails c
[1] pry(main)> Post.count
   (1.1ms)  SELECT COUNT(*) FROM "posts"
=> 20

By resetting db: reset, all the tables are dropped and regenerated. This will execute a seed that works only when there is a record. And by db: seed, you can see that 20 records have been added.

Introduction of Faker

It's nice to have a record, but the subject is hoge and the body is fuga. At this rate, if you get it from the API for some reason, it will be difficult to notice even if the same record is confused. However, it is troublesome to create a completely random character string each time, so Faker is useful.

Let's put it in for the time being.

Gemfile


...
group :development, :test do
...

+   "faker"
end
...
$ bundle

Let's try it out.

$ rails c
[1] pry(main)> Faker::Name.unique.name
=> "Miss Porter Kovacek"
[2] pry(main)> Faker::Name.name
=> "Felicita Durgan"
[3] pry(main)> Faker::Name.name
=> "Yong Weissnat"
[4] pry(main)> Faker::Name.name
=> "Sandie Oberbrunner"

Like this, it automatically returns random nouns and sentences each time it is executed. The words defined by default should be Check on Github. Not only people's names, animals, addresses and phone numbers, but also movies, manga, games, dramas, music. There are even Pokemon names and the Devil Fruit of ONE PIECE.

Put Faker in seeds

db/seeds/post_seeds.rb


# frozen_string_literal: true

unless Post.exists?
  20.times do
-    Post.create!(subject: "hoge", body: "fuga")
+    Post.create!(subject: Faker::Lorem.word, body: Faker::Lorem.paragraph)
  end
end
$ db:reset
$ db:seed
$ rails c
[1] pry(main)> Post.all
  Post Load (0.4ms)  SELECT "posts".* FROM "posts"
=> [#<Post:0x000000000636cbe8
  id: 1,
  subject: "quos",
  body: "Earum numquam qui. Impedit autem molestias. Ipsum adipisci eos.",
  created_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00,
  updated_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00>,
 #<Post:0x00000000063b5be0
  id: 2,
  subject: "vero",
  body:
   "Impedit distinctio saepe. Adipisci cupiditate officiis. Vel et deleniti.",
  created_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00,
  updated_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00>,

You can see that the records of random subject and body are created.

Japaneseize Faker

It is inconvenient to create a Japanese site if it is in English even though you put it in, so let's localize it. Since db: seed is executed in the dev environment, let's try to Japaneseize Faker in the dev environment.

config/environments/development.rb


 Rails.application.configure do
...

+  Faker::Config.locale = "ja"
 end

If you don't like Japaneseization all the time, you can put Faker :: Config.locale =" ja " in db / seeds / post_seeds.rb. Then run seed again.

$ rails db:reset
$ rails db:seed
$ rails c
[1] pry(main)> Post.all
  Post Load (0.3ms)  SELECT "posts".* FROM "posts"
=> [#<Post:0x0000000006480b88
  id: 1,
  subject: "Go",
  body: "Captain General Police Officer. Meishibokin Katamichi. Traditional Tokugawa super ~.",
  created_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00,
  updated_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00>,
 #<Post:0x00000000064fb928
  id: 2,
  subject: "French",
  body: "~ System last week. I'm going home. High price at the store.",
  created_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00,
  updated_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00>,

It has been successfully translated into Japanese. In addition, you can Check on Github if it is translated into Japanese. Conversely, what is not in this is still in English.

Continued

Introduction of # 9 serializer to build bulletin board API with authentication authorization in Rails 6 [To the serial table of contents]

Recommended Posts

# 8 seed implementation to build bulletin board API with authentication authorization in Rails 6
# 6 show, create implementation to build bulletin board API with authentication authorization in Rails 6
# 7 update, destroy implementation to build bulletin board API with authentication authorization in Rails 6
# 16 policy setting to build bulletin board API with authentication authorization in Rails 6
Introduced # 9 serializer to build bulletin board API with authentication authorization in Rails 6
Build a bulletin board API with authentication authorization in Rails 6 # 5 controller, routes implementation
Introduced # 10 devise_token_auth to build a bulletin board API with authentication authorization in Rails 6
Introducing # 15 pundit to build a bulletin board API with authentication authorization in Rails 6
Build a bulletin board API with authentication authorization in Rails 6 # 14 seed Execution time display
Build a bulletin board API with authentication authorization in Rails # 13 Add authentication header
Build a bulletin board API with authentication authorization in Rails # 17 Add administrator privileges
Build a bulletin board API with authentication and authorization with Rails # 18 ・ Implementation of final user controller
Build a bulletin board API with authentication and authorization with Rails 6 # 1 Environment construction
Build a bulletin board API with authentication authorization in Rails # 12 Association of user and post
Build a bulletin board API with authentication authorization in Rails 6 # 11 User model test and validation added
Build a bulletin board API with authentication authorization with Rails 6 # 2 Introducing git and rubocop
Building a bulletin board API with authentication authorization with Rails 6 Validation and test implementation of # 4 post
Build a bulletin board API with authentication authorization with Rails 6 # 3 RSpec, FactoryBot introduced and post model
How to build API with GraphQL and Rails
I implemented Rails API with TDD by RSpec. part3-Action implementation with authentication-
I tried to make a group function (bulletin board) with Rails
How to build Rails 6 environment with Docker
I implemented Rails API with TDD by RSpec. part1-Action implementation without authentication-
[Rails] Various ways to write in seed files
Try to create a bulletin board in Java
One way to redirect_to with parameters in rails
[Rails] How to build an environment with Docker
[How to insert a video in haml with Rails]
Using PAY.JP API with Rails ~ Implementation Preparation ~ (payjp.js v2)
How to query Array in jsonb with Rails + postgres
Build Rails (API) x MySQL x Nuxt.js environment with Docker
Implementation policy to dynamically save and display Timezone in Rails
[Rails] Create API to download files with Active Storage [S3]
[Apple login] Sign in with Apple implementation procedure (Ruby on Rails)
How to build Rails, Postgres, ElasticSearch development environment with Docker
How to set up a proxy with authentication in Feign
Things to keep in mind when using Sidekiq with Rails
Japaneseize using i18n with Rails
Implement LTI authentication in Rails
API creation with Rails + GraphQL
Login function implementation with rails
How to write Rails seed
[Rails] How to make seed
[Implementation procedure] Create a user authentication function using sorcery in Rails
I implemented Rails API with TDD by RSpec. part2 -user authentication-
What I was addicted to when implementing google authentication with rails
How to get boolean value with jQuery in rails simple form
How to rename a model with foreign key constraints in Rails
How to build Rails + Vue + MySQL environment with Docker [2020/09 latest version]
Steps to build a Ruby on Rails development environment with Vagrant