Вопрос

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.

Это было полезно?

Решение

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)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top