我有一些按钮可以清除集合,因此在开发/测试期间可以轻松地将网站恢复到原始状态,甚至无需重新启动服务器。
如何在控制器操作中执行seeds.rb的内容?
def purge
if Rails.env.production?
should_not_happen(severity: :armageddon)
else
# Well at least restore one admin account !
User.all.each(&:destroy)
regenerate_main_admin_accounts # Here I need to replay the content of `seeds.rb`
redirect_to(admin_dashboard_path)
end
end
注意:我的seeds.rb文件的内容大量使用了检查数据是否存在的条件和方法,我可以运行它10亿次——数据库中不会有重复的数据,所以我可以只运行它,即使只恢复1%的数据(我们在这里说的是dev/test环境,没有时间/资源压力)。
假设您意识到这不是一个好主意,并且可能涉及安全问题,则可以使用Rake::Task["<rake_command>"].execute
其中<rake_command>
是在rake
之后从命令行运行的语句。
require 'rake'
require 'rake/task'
# We want to make sure tasks are loaded without running them more than once:
Rake::Task.clear
<AppName>::Application.load_tasks
class SeedsController < ApplicationController
def run
Rake::Task["db:seed"].execute
redirect_to "/" # Or wherever...
end
end
出于好奇,你为什么要这么做?