如何设置 Rake 任务进行播种
(这实际上是一个关于 Rake 和 Rails 以及依赖关系的新手问题。尝试让我的头脑了解所有这些如何组合在一起)
基本上,我想要一个像 Seed.rb 一样但单独调用的 Rake 任务。它添加了开发环境的测试数据,而我的seed.rb则提供了所有环境的基础数据。
脚本 family_seed.rb 使用 FactoryGirl 生成一些记录。它看起来像这样:
require File.expand_path('../../config/environment', __FILE__)
require './spec/factories'
Family.delete_all
Member.delete_all
zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')
它与 bundle exec "ruby db/family_seeds.rb"
运行良好,但我的问题是如何使用 Rake 设置它。整个事情应该放在 Rake 任务中吗?相反,我如何设置一个调用脚本的任务,同时确保 Rails 开发环境在运行时可用?我不仅努力完成工作,而且努力以“正确”的方式完成工作。
(This is really a newbie question about Rake & Rails & dependencies in general. Trying to wrap my head around how all this fits together)
Basically, I want a Rake task that acts like seed.rb but is called separately. It adds test data for the development environment, while my seed.rb provides basic data for all environments.
The script, family_seed.rb, uses FactoryGirl to generate some records. It looks like this:
require File.expand_path('../../config/environment', __FILE__)
require './spec/factories'
Family.delete_all
Member.delete_all
zinsser = Factory.create(:family, :last_name=>'Zinsser', :first_name=>'Carl', :sim_id => '500')
blackburn = Factory.create(:family, :last_name=>'Blackburn', :first_name=>'Greg', :sim_id => '501')
It runs fine with bundle exec "ruby db/family_seeds.rb"
, but my question is how to set it up with Rake. Should the whole thing be placed inside a Rake task? How could I, instead, set up a task that would call the script, while ensuring that the Rails development environment is available when it runs? I'm trying not just to get the job done, but to do it in a "right" way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决这个问题的一种方法是在 lib 中创建一个类或模块(这使得编写测试变得更容易,并使代码更可重用):
如何创建 rake 任务:
我会小心地允许诸如 Family 之类的事情.delete_all 和 Member.delete_all 使用过于随意。稍后您可能会在生产数据库上调用一些您无意的内容,很容易搬起石头砸自己的脚。
如何运行 rake 任务:
在命令中运行它,如下所示:
One way to approach this would be to create a class or module in lib (this makes it easier to write tests for, and makes the code more reusable):
How to create the rake task:
I'd be careful with allowing things like Family.delete_all and Member.delete_all to be too freely used. You could easily shoot yourself in the foot later on by calling something you didn't mean to on a production db.
How to run the rake task:
Run it in your command like with the following:
创建一个 rake 任务并需要 :environment
后就可以运行此任务
rake delete_all
Create a rake task and require :environment
After you can run this task
rake delete_all