[Ruby] A note about the seeding feature of Ruby on Rails

less than 1 minute read

Introduction

I am a beginner. I am making an application using Ruby and Ruby on Rails. It also serves as a memorandum, so please point out any mistakes.

What is seed function

A function that allows you to easily pour initial data after creating a database.

Which file to use

Describe the code you want to flow as initial data in db/seeds.rb, OK by doing rails db:seed in the terminal. Even if you execute it, nothing will be displayed in the terminal, but if there is no problem with the data it should have been poured.

How to describe in file

Example) Pour 5 data into name column and description column of products table

5.times do |i|
  Product.create(name: "Product ##{i}", description: "A product.")
end

I am using the times method, but there is no problem even if I write it line by line.

Summary

  • Seed function is a function that can pour initial data after database creation
  • Describe the data you want to put in db/seeds.rb
  • You can run it by doing rails db:seed in the terminal

Reference

Rails Guide v6.0 https://railsguides.jp/active_record_migrations.html