如何使用 Seed.rb 有选择地填充开发和/或生产数据库?
我正在使用 seeds.rb 来填充我的开发和生产数据库。我通常用虚拟数据填充第一个,然后用我的应用程序运行所需的实际最小数据(例如第一个用户等)填充后者。
如何在 Seed.rb 中指定每个数据的环境?
鉴于我知道“group”是一个 Gemfile 方法,我希望为 Seed.rb 实现相同的行为。
例如,我想在我的seed.rb中编写类似的内容:
group :development do
# development specific seeding code
end
group :production do
# production specific seeding code
end
# non-specific seeding code (it always runs)
这样就能够使用以下方式调用特定于开发的代码和非特定的代码,
$ rake db:seed
并使用以下方式调用特定于生产的代码和非特定的代码:
$ rake db:seed RAILS_ENV=production
谢谢
I am using seed.rb to populate both my development and production database. I usually populate the first with dummy data and the latter with the real minimal data that my app needs to run (e.g. the first user and so on).
How can I specify in seed.rb for what environment each data is?
Given that I know "group" to be a Gemfile method, I'd like to achieve the same behavior for seed.rb.
E.g. I'd like to write something like this in my seed.rb:
group :development do
# development specific seeding code
end
group :production do
# production specific seeding code
end
# non-specific seeding code (it always runs)
This to be able to call both the development-specific and the non-specific code with
$ rake db:seed
And to call both the production-specific and the non-specific code with:
$ rake db:seed RAILS_ENV=production
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
seeds.rb
只是一个普通的 ruby 文件,因此有多种方法可以实现此目的。案例陈述怎么样?seeds.rb
is just a plain ruby file, so there are several ways you could approach this. How about a case statement?另一种方法可以是创建:
然后在 db/seeds.rb 中:
然后在相应文件中编写要为每个环境运行的代码。
Another approach could be creating:
Then in
db/seeds.rb
:Then write the code you want to run for each environment in the respective file.
另一种方法,与@fabro的答案非常相似:
将文件夹 seeds 添加到
db/
中,其中包含环境名称和另一个名为 common.rb 的文件夹,这样您就可以在
seed.rb
中得到如下内容:I perfer running一笔交易中的种子
another approach, quite similar to @fabro's answer:
add a folder seeds to
db/
with the environment names and another named common.rb, so you get something like:than, in your
seed.rb
:I perfer running the seed in one transaction