Rails 如何创建数据模式种子数据 [英] Rails how to create data schema seed data

查看:34
本文介绍了Rails 如何创建数据模式种子数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法自动生成种子数据文件并创建种子数据,就像你在 Laravel 下面的链接中看到的那样?

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 数据库迁移 &种子

我在另一个应用程序上看到在 Rails 的 db 文件夹下创建了一些带时间戳的文件,其中包含种子数据.

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?

推荐答案

我建议你使用 Fabrication gem 和 Faker.

I suggest you to use the combination of Fabrication gem and Faker.

Fabrication 允许您编写一个模式来构建您的对象,而 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.

这就是制造商的样子:

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

在您的 db/seed.rb 中,您可以像这样使用它:

In your db/seed.rb you can use it like this:

50.times { Fabricate(:user) }

您将获得 50 个带有随机用户名和testtest"密码的假用户 :)

You will get 50 fake users with random username and "testtest" password :)

这篇关于Rails 如何创建数据模式种子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆