0

I have a form_with that submits remotely and works perfectly for almost everyone. However, every once in a while, a user gets this error:

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

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

View:

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

Action:

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

Response:

It's in a file called create.js.erb

Question: I have looked everywhere but I have not idea why certain users request HTML instead of JS, which is what every other user gets. What am I missing? I really don't want to support HTML responses.

Breno Gazzola
  • 2,092
  • 1
  • 16
  • 36
  • You mean you want to answer every requests as if it was a `JSON` request? – EmmanuelB Nov 01 '18 at 19:58
  • Not quite. `form_with` submits all requests using XHR and expects a JS response. But a small part of the requests seem to be submitting through standard HTML and therefore expecint HTML responses. I want to understand why this is happening. – Breno Gazzola Nov 02 '18 at 17:34

1 Answers1

0

Your server may be receiving requests in different formats and trying to serve them accordingly:

  • GET www.my_server.com/resource.html
  • GET www.my_server.com/resource.json
  • Or a strange format GET www.my_server.com/resource.what

This is the desired behavior in Rails. Take a look into this question about how to change the default format for your routes, or you may change them all to be of type json in your ApplicationController:

class ApplicationController < ActionController::Base
  before_action :set_default_response_format

  protected

  def set_default_response_format
    request.format = :json
  end
end

The important line is request.format = :json, which can be used in only one controller or just one of its actions.

If you want your code to always respond in json, then you may want to take a look into Using Rails for API-only Applications

EmmanuelB
  • 1,236
  • 9
  • 19
  • Yes, I'm receiving requests for different formats and that's what I don't understand. `form_with` defaults to XHR requests and expects JS responses. And it works. But a small subset of users, somehow, are submitting the form through standard HTML and expecting HTML as a response. I want to understand why that happens and how to prevent it. – Breno Gazzola Nov 02 '18 at 17:35
  • Try `form_with(model: [@event, @testimonial], format: :json)`. [This answer](https://stackoverflow.com/a/45071735/8304905) may help you. – EmmanuelB Nov 02 '18 at 17:51