[RUBY] [Rails] Manage data for each seed file

The team is creating a clone site for a certain flea market app. At that time, I had a little trouble handling the seed file, so I will leave it as a memorandum.

What you want to do

When listing a product, the "state of the product", "shipping fee" ..etc, etc. Put the value in the database first so that you can select it from the pull-down menu

Like this スクリーンショット 2020-06-29 17.41.45.png


1. Creating a rake task

Create seed.rake directly under lib / tasks / and describe the following


 Dir.glob(File.join(Rails.root, 'db', 'seeds', '*.rb')).each do |file|
   desc "Load the seed data from db/seeds/#{File.basename(file)}.
   task "db:seed:#{File.basename(file).gsub(/\..+$/, '')}" => :environment do

2. Create each seed file

Create a db / seeds directory and create a file of "model name.rb where you want to put data" in it For the time being, create Condition.rb that shows the state of the product.


conditions = Condition.create([
  {condition: "New / unused"},
  {condition: "Nearly unused"},
  {condition: "No noticeable scratches or stains"},
  {condition: "Slightly scratched and dirty"},
  {condition: "There are scratches and dirt"},
  {condition: "Overall poor condition"}])

3. Run

All you have to do is execute the following command in the terminal

bundle exec rake  db:seed:condition

You have put the data in the conditions table! スクリーンショット 2020-06-29 18.18.27.png

However, a problem has occurred ...

If it is a local environment, it was fine as it is, but when deploying to a production environment I didn't know how to read each seed file I created, so I couldn't reflect the data.


Added the following description to seeds.rb


require "./db/seeds/condition.rb

When I executed the following command in the terminal of the production environment, it was reflected properly


require "./db/seeds/condition.rb

At the end

I wonder if it could have been made a little easier by using active hash, but Since there is a delivery date, I implemented it this way once I would like to know if there is another good way

Reference article

-Allow Rails to divide seed data and execute it -Rails-seed file is divided and managed

Recommended Posts

[Rails] Manage data for each seed file
[Rails] Initial data creation with seed
[Rails] Get standard input for multi-line data
I summarized the naming conventions for each Rails
Save data from excel file using Rails gem roo
Create an EC site with Rails5 ⑥ ~ seed data input ~
Rails6: Input the initial data of ActionText using seed
Summary of file reading method for each Java file format
Utilization of seed file
[Rails] Prepare dummy data to be used for testing [Faker]
[Rails] Implemented a pull-down search function for Active Hash data