multiple seeds in rails 6
Step 1: Create a new Ruby on Rails migration file to add a seeds table.
rails generate migration CreateSeeds
Step 2: Open the generated migration file (db/migrate/xxxxxxxxxxxxxx_create_seeds.rb
) and define the schema for the seeds table.
class CreateSeeds < ActiveRecord::Migration[6.0]
def change
create_table :seeds do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
Step 3: Run the migration to create the seeds table.
rails db:migrate
Step 4: Create seed data files in the db/seeds
directory. For example, you can create 01_seeds.rb
, 02_seeds.rb
, etc.
# db/seeds/01_seeds.rb
Seed.create(name: 'Seed 1', description: 'Description for Seed 1')
# db/seeds/02_seeds.rb
Seed.create(name: 'Seed 2', description: 'Description for Seed 2')
Step 5: Load the seed data into the database.
rails db:seed
Step 6: Optionally, use specific seed data files.
rails db:seed:replant # Truncates tables and then loads seeds
rails db:seed:replant:01_seeds # Truncates tables and loads only 01_seeds.rb
Step 7: Rollback the last seed operation.
rails db:seed:undo
Step 8: Rollback specific seed data file.
rails db:seed:undo:01_seeds
Step 9: Rollback and redo the seeds.
rails db:seed:redo
Step 10: Load specific seed data files without affecting the database.
rails db:seed:replant:noop:01_seeds
Step 11: View the status of seed data.
rails db:seed:status
Step 12: Clear the seeds table.
rails db:seed:clear
Note: Adjust the table name and attributes in the migration and seed data files according to your application's requirements.