Rake 任务无法正确加载:环境 [英] Rake task failing to load :environment properly

查看:47
本文介绍了Rake 任务无法正确加载:环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个自定义的 rake 任务...

I'm running a custom rake task...

namespace :import do

  desc "Import terms of service as HTML from stdin"
  task :terms => :environment do
    html = STDIN.read
    settings = ApplicationWideSetting.first
    settings.terms_and_conditions = html
    if settings.save
      puts "Updated terms of service"
    else
      puts "There was an error updating terms of service"
    end
  end

end

production 环境中运行任务时,模型 ApplicationWideSetting 被报告为未定义.但是,在其他环境(即developmentstagingtest)上运行任务时,任务运行良好.

The model ApplicationWideSetting is reported as undefined when running the task in the production environment. However, when running the task on other environments (ie. development, staging, test.) the task runs fine.

在 rails 控制台中运行该过程,在所有环境中都可以完成.

Running the process in rails console, in all environments, completes ok.

有谁知道发生了什么,我可以检查一下吗?

Does anyone know what's going on, things I could check?

注意:我用

puts Rails.env 

检查 shell 环境变量 RAILS_ENV 是否正确设置/读取.我还尝试过在 :environment 依赖项声明周围使用和不使用方括号.

To check the shell environment var RAILS_ENV was getting set/read correctly. I've also tried both with and without the square brackets around the :environment dependency declaration.

附加信息:Rails v3.2.14

additional info: Rails v3.2.14

更多信息:我已经设置了一个全新的 rails 应用程序,并且该脚本在任何环境中都可以正常工作.由于有问题的安装是一个真正的生产环境,我必须设置另一个部署并彻底检查它.我找到的更多信息.

further info: I've setup a completely fresh rails app, and the script works fine in any environment. Since the install in question is a real production environment, I'll have to setup another deploy and check it thoroughly. More info as I find it.

推荐答案

简而言之,Rails 在生产环境中运行 rake 任务时不会预先加载模型(或其他任何东西).

In a nutshell, Rails doesn't eager load models (or anything else) when running rake tasks on Production.

使用模型的最简单方法是在开始 rake 任务时 require 它,它应该按预期工作,在这种情况下:

The simplest way to work with a model is to require it when you begin the rake task, and it should work as expected, in this case:

# explicitly require model
require 'application_wide_setting'

可以通过以下方式预先加载整个 rails 应用程序:

It's possible to eager load the entire rails app with:

Rails.application.eager_load!

但是,您可能会遇到一些初始化程序(即设计)的问题

However, you may have issues with some initializers (ie. devise)

这篇关于Rake 任务无法正确加载:环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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