Rake task failing to load :environment properly

[亡魂溺海] 提交于 2019-12-10 10:31:31

问题


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

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.

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

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

note: I ran the task with

puts Rails.env 

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.

additional info: Rails v3.2.14

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.


回答1:


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

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'

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)



来源:https://stackoverflow.com/questions/18506933/rake-task-failing-to-load-environment-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!