模块在dev中加载但不在生产中加载(Rails / Heroku)

时间:2018-01-27 22:40:34

标签: ruby-on-rails ruby heroku

我正在尝试加载的模块,在开发中工作,但不在生产中:

# /app/controllers/concerns/response.rb
module Response
  def json_response(object, status = :ok)
    render json: object, status: status
  end
end

我的应用程序控制器:

class ApplicationController < ActionController::API
  include Response
  include DeviseTokenAuth::Concerns::SetUserByToken
  include ActionController::MimeResponds
end

我可以在开发中使用json_response没问题,但不能在生产中使用。发送到heroku时,我收到此错误:

/app/app/controllers/application_controller.rb:2:in `<class:ApplicationController>': uninitialized constant ApplicationController::Response (NameError)

该模块存在于/ app /中,因此应该自动加载。我错过了什么?

1 个答案:

答案 0 :(得分:0)

尝试以下命令:

bundle exec rails r 'puts ActiveSupport::Dependencies.autoload_paths'

它应该显示autoload_paths包含app/controllers/concerns。如果没有,请将其添加到config/application.rb

config.autoload_paths += %W(#{config.root}/app/controllers/concerns)

如果不起作用,另一种方法是尝试将concern包裹在忧虑模块中:

module Concerns
  module Response
    def json_response(object, status = :ok)
      render json: object, status: status
    end
  end
end

在应用程序控制器中:

class ApplicationController < ActionController::API
  include Concerns::Response
end

修改

默认情况下,自动加载路径导致的问题可能会在生产中失效(https://blog.bigbinary.com/2016/08/29/rails-5-disables-autoloading-after-booting-the-app-in-production.html)。所以请尝试在eager_load_path中添加它:

# In application.rb
config.eager_load_paths += %W(#{config.root}/app/controllers/concerns)