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

1 minute read

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

What you want

When listing items, “state of goods”, “delivery fee”..etc Populate the database first so that you can select from the pull-down

Like this Screenshot 2020-06-29 17.41.45.png


1. Creating a rake task

Create seed.rake directly under lib/tasks/ and list 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 “model name.rb you want to put data in.” For the time being, create a Condition.rb that represents the state of the product


conditions = Condition.create((
  {condition: "New/unused"},
  {condition: "close to unused"},
  {condition: "No noticeable scratches or stains"},
  {condition: "Slightly scratched or dirty"},
  {condition: "Scratch or dirt"},
  {condition: "Overall condition"}])

3. Execution

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

bundle exec rake db:seed:condition

You have entered data into the conditions table! ![Screenshot 2020-06-29 18.18.27.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/656249/81ab5667-e0ea-76e8-5769-(4591e9473cce.png)

Has a problem…

If it’s a local environment, it’s fine as it is, but when deploying to the production environment I could not reflect the data because I did not know how to read each created seed file


Added the following description to seeds.rb


require "./db/seeds/condition.rb

When I execute the following command in the terminal of the production environment, it is reflected properly


require "./db/seeds/condition.rb

At the end

I wonder if I could have made it a little easier with active hash, but There is also a delivery date, so I implemented this method once I would like to know if there is another good way

Reference article

Allow splitting seed data in Rails to executeRails/seed file is divided and managed