【问题标题】:Intermittent ActionController::UnknownFormat error in remote form with Rails 5Rails 5 远程形式的间歇性 ActionController::UnknownFormat 错误
【发布时间】:2018-11-01 18:27:14
【问题描述】:

我有一个form_with,它可以远程提交并且几乎适用于所有人。但是,每隔一段时间,用户就会收到此错误:

ActionController::UnknownFormat: TestimonialsController#create is missing a template for this request format and variant.

request.formats: ["text/html"]
request.variant: []

查看:

<%= form_with(model: [@event, @testimonial]) do |form| %>
...
<% end %>

行动:

def create
  @testimonial = @event.testimonials.find_or_initialize_by(user: Current.user)
  @testimonial.assign_attributes testimonial_params.merge({status: :pending})
  @testimonial.save
end

回应:

它在一个名为create.js.erb的文件中

问题:我到处看了,但我不知道为什么某些用户请求 HTML 而不是 JS,这是每个其他用户都得到的。我错过了什么?我真的不想支持 HTML 响应。

【问题讨论】:

  • 你的意思是你想像JSON请求一样回答每个请求?
  • 不完全。 form_with 使用 XHR 提交所有请求并期望 JS 响应。但一小部分请求似乎是通过标准 HTML 提交的,因此期待 HTML 响应。我想了解为什么会这样。

标签: ruby-on-rails actioncontroller


【解决方案1】:

您的服务器可能正在接收不同格式的请求并尝试相应地为它们提供服务:

  • GET www.my_server.com/resource.html
  • GET www.my_server.com/resource.json
  • 或者奇怪的格式GET www.my_server.com/resource.what

这是 Rails 中期望的行为。查看this question 了解如何更改路线的默认格式,或者您可以在ApplicationController 中将它们全部更改为json 类型:

class ApplicationController < ActionController::Base
  before_action :set_default_response_format

  protected

  def set_default_response_format
    request.format = :json
  end
end

重要的一行是request.format = :json,它只能用在一个控制器或它的一个动作中。

如果您希望您的代码始终以json 响应,那么您可能需要查看Using Rails for API-only Applications

【讨论】:

  • 是的,我收到了不同格式的请求,这就是我不明白的。 form_with 默认为 XHR 请求并期望 JS 响应。它有效。但不知何故,一小部分用户正在通过标准 HTML 提交表单并期望 HTML 作为响应。我想了解为什么会发生这种情况以及如何预防。
  • 试试form_with(model: [@event, @testimonial], format: :json)This answer 可以帮到你。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
相关资源
最近更新 更多