Is there a way to auto generate a seed data file and create seed data like what you would see in Laravel in below link?
Laravel Database Migrations & Seed
I've seen some timestamped files created under db folder of Rails on another app with timestamp which had seed data included.
What would be good approach to create this?
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.
I suggest you to use the combination of Fabrication gem and Faker.
Fabrication allows you to write a pattern to build your objects and Faker gives you fake data like names, emails, phone numbers and so on.
This is how a fabricator looks like:
Fabricator(:user) do
username { Faker::Internet.user_name }
name { Faker::Name.first_name }
surname { Faker::Name.last_name }
password { "testtest" }
password_confirmation { |attrs| attrs[:password] }
end
In your db/seed.rb
you can use it like this:
50.times { Fabricate(:user) }
You will get 50 fake users with random username and "testtest" password :)
If you're looking to create real seed data (for a lookup table of statuses for example) you can add something like the following to your db\seeds.rb
file.
# Statuses
# Will insert 5 rows in statuses table
['Not Started', 'In Progress', 'On Hold', 'Complete', 'Not Applicable'].each do |status|
Status.find_or_create_by(status: status)
end
Then, from your console:
$ rake db:seed
To create the data when running tests you can use:
load "#{Rails.root}/db/seeds.rb"
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