在 Rails 中填充开发数据库的最佳方法 [英] Best way to fill development db in rails
本文介绍了在 Rails 中填充开发数据库的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要用数据填充 test 开发数据库,例如来自 factorygirl
的数据,但我想从 Rails 控制台使用它.
我如何将示例数据放入 db 以便我可以从控制台获取它并在那里进行一些测试?
I need to fill the test development database with data, for example from factorygirl
, but I'd like to use it from rails console.
How I put example data in db so I can fetch it from console and do some test there?
推荐答案
Faker 也是一个不错的解决方案.
Faker is also a good solution.
这是我的 lib/tasks/sample_data.rake
的样子.我用 rake db:populate
运行它.
Here's how my lib/tasks/sample_data.rake
looks like. I run it with rake db:populate
.
使用随机信息创建 50 个条目.
Creates 50 entries with random info.
require 'faker'
namespace :db do
desc "Fill database with sample data"
task :populate => :environment do
Rake::Task['db:reset'].invoke
50.times do |n|
name = Faker::Company.name
year = 1900+rand(111)
rating = 1+rand(10)
watched = (1 == rand(2) ? true : false)
imdb_id = rand(1000000)
Movie.create!(:name => name,
:year => year,
:rating => rating,
:watched => watched,
:imdb_id => imdb_id)
end
end
end
这篇关于在 Rails 中填充开发数据库的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文