lza*_*zap 16 sql postgresql rake ruby-on-rails-3
我希望有一个rake任务来截断所有表.我在互联网上找到了一个,但它只适用于Rails 2并且不适用于Rails 3(问题在于获取数据库连接).
rake db:reset
不是一个选项,因为我使用的是PostgreSQL,它也会丢弃用户.因此迁移失败.我只想清除数据.
你们有什么事吗?
kik*_*ito 35
我通过谷歌找到了这个,然后我得到了比批准的更简单的解决方案,所以这里是:使用database_cleaner gem.这是步骤.
在你的Gemfile中(修改后执行包):
gem 'database_cleaner' # you might want to limit this to the dev and staging group
Run Code Online (Sandbox Code Playgroud)
使用该gem,该语句DatabaseCleaner.clean_with :truncation
将截断数据库.将它添加到rake任务是微不足道的:
# tasks/db/clean.rake
namespace :db do
desc "Truncate all existing data"
task :truncate => "db:load_config" do
DatabaseCleaner.clean_with :truncation
end
end
Run Code Online (Sandbox Code Playgroud)
而已.您也可以直接使用文件中的DatabaseCleaner.clean_with :truncation
行,db/seeds.rb
这样您就不会忘记在播种前截断数据库.
lza*_*zap 19
所以我将链接的例子编辑成:
namespace :db do
desc "Truncate all existing data"
task :truncate => "db:load_config" do
begin
config = ActiveRecord::Base.configurations[::Rails.env]
ActiveRecord::Base.establish_connection
case config["adapter"]
when "mysql", "postgresql"
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("TRUNCATE #{table}")
end
when "sqlite", "sqlite3"
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("DELETE FROM #{table}")
ActiveRecord::Base.connection.execute("DELETE FROM sqlite_sequence where name='#{table}'")
end
ActiveRecord::Base.connection.execute("VACUUM")
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
这个例子基于Chris Ledet的代码(谢谢)并与Rails 3.X一起使用.
谢谢你的所有提示.
小智 10
根据Chris Ledet的回答,这变得更加简单:
ActiveRecord::Base.connection.tables.each do |table|
ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table};")
end
Run Code Online (Sandbox Code Playgroud)
您可以随时迁移到版本0,如下所示:
rake db:migrate VERSION=0
Run Code Online (Sandbox Code Playgroud)
这样你甚至不必截断你的表,然后你可以再次迁移.唯一的问题是您需要down
迁移才能正常工作.
该解决方案并在轨道3,工作尽管该版本是基于时间戳.
此解决方案如下所示:https://stackoverflow.com/a/1196822/241367
此外,假设您的schema.rb
是最新的,您可以始终运行以下命令:
rake db:schema:load
Run Code Online (Sandbox Code Playgroud)
而作为@kikito建议,可以运行database_cleaner
(这是什么cucumber
和rspec
喜欢测试之间使用),如下所示:
DatabaseCleaner.clean_with :truncation
Run Code Online (Sandbox Code Playgroud)