为什么 Rails 无法在生产环境中检测到 AJAX 请求?

Why Rails fails to detect AJAX request in production?

我正在使用 rails 5.2.4.1,我想知道为什么当我尝试访问 API 端点时出现此错误:

ActionView::MissingTemplate (Missing template api/schools/classrooms, application/classrooms with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :haml]}.

这是我的操作:

def classrooms
    render json: {classrooms: user.daip.class_rooms.as_json(:include => [:users]), max_classrooms: user.daip.classrooms} , content_type: 'application/json'
  end

我还尝试将默认 json 响应添加到所有 classrooms_controller 为:

resources :schools, :defaults => { :format => 'json' }

我尝试将 .json 添加到路由中,但没有成功

我该如何调试它?因为它在本地工作,而不是在生产服务器上工作?我在 passenger 上使用 nginx。

可能是什么问题?

编辑

我也试过:

ActiveModel::Serializer.config.adapter = ActiveModel::Serializer::Adapter::JsonApi

EDIT2 我发现 header HTTP_ACCEPT 被传递为:

"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9"

我设置成application/json, text/plain, */*,还是rails找模板!!

EDIT3

我尝试将默认请求设置为 json 为:

request.format = :json

我尝试将 format.json 用作:

def classrooms
    request.format = :json
    format.json {
    render plain: {classrooms: user.daip.class_rooms.as_json(:include => [:users]), max_classrooms: user.daip.classrooms}.to_json , content_type: 'application/json'
    }
  end

我仍然有同样的错误,正在搜索模板..

EDIT4

这是我的请求 headers:

Host: myapp.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/json
Referer: https://myapp.com/en/api/school-admin
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
TE: Trailers
Origin: https://myapp.com
Content-Length: 0

和路线:

namespace :api, defaults: {format: :json} do
    get 'classrooms' => 'schools#classrooms'
  end

在经历了前几个小时的挫折之后,我决定自己调试我试图创建 json 对象的代码。我传递了一个空的 json 对象,然后,我得到了带有空 json 对象的状态 200 响应!所以,错误 ActionView::MissingTemplate 完全是误导!!,让我看不到真正的错误。我在 rails 控制台中 运行 代码 user.daip.class_rooms.as_json(:include => [:users]),我得到了这个错误:

Cannot have a has_many :through association 'ClassRoom#users' which goes through 'ClassRoom#class_rooms_users' before the through association is defined

查了class_room型号,哦!我只需要翻转这些行:

  has_many :users, through: :class_rooms_users
  has_many :class_rooms_users

至:

  has_many :class_rooms_users 
  has_many :users, through: :class_rooms_users

那真是个悲伤的故事,座右铭是,当一切似乎都很好时,永远不要相信错误消息,悲伤的开发者。