Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split seeds.rb file [duplicate]

Tags:

My seeds.rb file is getting very large. What is the best way to refactor the data in the file?

Can I put the data into various files and require them in the seeds.rb file?

like image 684
chief Avatar asked Oct 31 '11 18:10

chief


People also ask

What is seed rb file?

The seeds.rb file is where the seed data is stored, but you need to run the appropriate rake task to actually use the seed data. Using rake -T in your project directory shows information about following tasks: rake db:seed. Load the seed data from db/seeds.rb. rake db:setup.

What is Seeds rb in rails?

Rails seed files are a useful way of populating a database with the initial data needed for a Rails project. The Rails db/seeds. rb file contains plain Ruby code and can be run with the Rails-default rails db:seed task.

What does DB seed do?

Database seeding is populating a database with an initial set of data. It's common to load seed data such as initial user accounts or dummy data upon initial setup of an application.

How do I run a specific seed in rails?

To run the default seeds. rb file, you run the command rake db:seed . If I create a file in the db directory called seeds_feature_x. rb , what would the rake command look like to run (only) that file?


1 Answers

We store all our seeds inside the folder db/seeds and inside the db/seeds.rb we write the following:

Dir[File.join(Rails.root, 'db', 'seeds', '*.rb')].sort.each { |seed| load seed } 

We sort the files alphabetically before loading them, so we can make sure the files are processed in order (by choosing the filenames wisely, e.g. something like 01_operators.rb, 02_companies.rb, 03_products.rb ...).

Hope this helps.

like image 80
nathanvda Avatar answered Sep 20 '22 18:09

nathanvda