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?
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.
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.
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With