Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does Rails ignore content-type when accepts is different?
    primarykey
    data
    text
    <p>I have a RESTful controller:</p> <pre><code>class Api::V1::DevicesController &lt; ApplicationController before_filter :require_user respond_to :json # PUT /api/v1/devices/1 def update @device = Device.find(params[:id]) authorize! :update, @device @device.update_attributes(params[:device]) respond_with @device end end </code></pre> <p>And some JS on the client side:</p> <pre><code>$("#click-me").on('click', function() { $.ajax({ type: "PUT", url: '/api/v1/devices/' + $(this).data('device-id'), dataType: 'json', accept: 'application/json', data: {device: {user_id: null}, format: 'json'}, success: function () { alert("Booya!"); } }) }); </code></pre> <p>When the AJAX gets fired, by default, jQuery sends a JS object as a URL encoded string. And a <code>Content-Type:application/x-www-form-urlencoded</code> which is fine. And because I set <code>dataType</code> to <code>'json'</code>, it sets <code>Accept:application/json, text/javascript, */*; q=0.01</code>, which also seems fine.</p> <p>However when Rails gets the request, it treats the post body as JSON, even tho content-type is URL Encoded. Is this a bug?</p> <p>My solution so far is to cast the JS object as JSON (<code>JSON.stringify({device: {user_id: null}, format: 'json'})</code>) and just submit it.</p> <p>But that doesn't feel very good, surely Rails should handle Content-Type and Accept separately. This app is in 3.0.17. Perhaps it's an issue with earlier versions?</p> <p><strong>UPDATE:</strong></p> <p>Turns out the 422 I was receiving was a validation failure, and Rack is smart enough to deal with varying Content-Type and Accept headers. Duh.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload