Rake任务以截断Rails 3中的所有表 [英] Rake task to truncate all tables in Rails 3

查看:72
本文介绍了Rake任务以截断Rails 3中的所有表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个rake任务来截断所有表。我已经找到了一个,但只能用于Rails 2,而不能用于 Rails 3 (问题在于获得数据库连接)。

I would like to have a rake task for truncating all the tables. I have found one on the internet, but it is supposed only for Rails 2 and does not work for Rails 3 (problem is in getting a database connection).

rake db:reset 不是一个选项,因为我使用的是PostgreSQL,它也会删除用户。因此,迁移失败。我只想清除数据。

rake db:reset is not an option, because I am using PostgreSQL and it also drops the user. Therefore migration fails. I only want to clear the data.

你们对我有帮助吗?

推荐答案

我已经通过google找到了,然后得到了比批准的解决方案简单得多的解决方案,所以这里是:使用 database_cleaner gem。以下是步骤。

I've found this via google, and then I got a much simpler solution than the one approved, so here it is: Use the database_cleaner gem. Here're the steps.

在您的Gemfile中(修改后执行捆绑):

In your Gemfile (execute bundle after modifying):

gem 'database_cleaner' # you might want to limit this to the dev and staging group

有了该gem后,语句 DatabaseCleaner.clean_with:truncation 将截断数据库。将其添加到rake任务中很简单:

With that gem in place, the statement DatabaseCleaner.clean_with :truncation will truncate the database. Adding it to a rake task is trivial:

# tasks/db/clean.rake

namespace :db do

  desc "Truncate all existing data"
  task :truncate => "db:load_config" do
    DatabaseCleaner.clean_with :truncation
  end

end

就是这样。您也可以直接在 db / seeds.rb 文件中使用 DatabaseCleaner.clean_with:truncation 行,这样就可以不要忘记在播种之前截断数据库。

That's it. You can also use the DatabaseCleaner.clean_with :truncation line inside your db/seeds.rb file directly so that you don't forget to truncate the database before seeding.

这篇关于Rake任务以截断Rails 3中的所有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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