当接受不同时,为什么Rails会忽略内容类型?

时间:2012-10-01 10:49:14

标签: ruby-on-rails ajax

我有一个RESTful控制器:

class Api::V1::DevicesController < 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

客户端的一些JS:

$("#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!"); 
    }
  })
});

当AJAX被触发时,默认情况下,jQuery将JS对象作为URL编码字符串发送。 一个Content-Type:application/x-www-form-urlencoded很好。因为我将dataType设置为'json',所以设置Accept:application/json, text/javascript, */*; q=0.01,这似乎也很好。

但是当Rails获取请求时,它会将帖子主体视为JSON,即使内容类型是URL编码。这是一个错误吗?

到目前为止,我的解决方案是将JS对象转换为JSON(JSON.stringify({device: {user_id: null}, format: 'json'}))并提交它。

但这感觉不太好,当然Rails应该单独处理Content-Type和Accept。这个程序是在3.0.17。也许这是早期版本的问题?

更新

原来我收到的422是验证失败,而Rack非常聪明,可以处理不同的Content-Type和Accept标头。咄。

1 个答案:

答案 0 :(得分:0)

这可能是由于

dataType: 'json',

行,通知服务器您的请求内容是JSON。