Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails how to create data schema seed data

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?

like image 738
Passionate Engineer Avatar asked Sep 15 '13 15:09

Passionate Engineer


People also ask

What is db seed 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.


2 Answers

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 :)

like image 61
Luca Marturana Avatar answered Oct 02 '22 18:10

Luca Marturana


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"

like image 29
Stenerson Avatar answered Oct 02 '22 16:10

Stenerson