正在从 Rails 应用程序执行 seeds.rb
Executing seeds.rb from Rails application
我有一些按钮可以清除集合,因此在 development/test 期间很容易将网站恢复到原始状态,甚至无需重新启动服务器。
如何在控制器操作中执行 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 文件的内容广泛使用了检查数据是否存在的条件和方法,我可以 运行 它十亿次,其中不会有重复的数据数据库,所以我可以 运行 它,即使只恢复 1% 的东西(我们在这里谈论 dev/test 环境,没有 time/resource 压力)。
假设您知道这不是一个好主意,并且可能涉及安全问题,您可以使用 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
出于好奇,你为什么要这样做?
我有一些按钮可以清除集合,因此在 development/test 期间很容易将网站恢复到原始状态,甚至无需重新启动服务器。
如何在控制器操作中执行 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 文件的内容广泛使用了检查数据是否存在的条件和方法,我可以 运行 它十亿次,其中不会有重复的数据数据库,所以我可以 运行 它,即使只恢复 1% 的东西(我们在这里谈论 dev/test 环境,没有 time/resource 压力)。
假设您知道这不是一个好主意,并且可能涉及安全问题,您可以使用 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
出于好奇,你为什么要这样做?