Rails how to create data schema seed data

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

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?

回答1:

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



回答2:

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"



回答3:

Theres a fairly useful gem for seed data called Faker. It's somewhat limited in the type of random data it generates, but I find it quite useful for simple things such as names, addresses, etc.

Of course you have to put it in a loop and write the query to insert it into the DB yourself.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!