【问题标题】:$http service adding unwanted JSON key to request data$http 服务添加不需要的 JSON 密钥来请求数据
【发布时间】:2015-04-29 16:37:00
【问题描述】:

我有一个简单的服务,用于将数据发布到 Rails 控制器。

我的服务看起来像这样:

app.service('autoRulesService', function($http) {
  return({
    createRule: createRule
  });

  function createRule() {
    var request = $http({
      method: 'POST',
      url: '/rules.json',
      data: { one: 'two }
    });

    return request.then(handleSuccess, handleError);
  }

  function handleSuccess() {
    // body omitted...
  }
  function handleError() {
    // body omitted...
  }
});

我以非常标准的方式在我的控制器中使用该服务:

$scope.saveRule = function() {
  rulesService.createRule().then(function() {
    // do stuff...
  });
}

问题是当我在 Rails 日志中检查发送的数据时,我在参数中得到了一个奇怪的不需要的键。 "rule" 参数从何而来?

Processing by AutoAnalysis::RulesController#create as JSON
   Parameters: {"one"=>"two", "rule"=>{}}

它没有出现在请求负载中(在 Chrome 开发工具中检查过)

而且我的控制器操作非常标准(也没有前置过滤器):

class RulesController < ApplicationController
  def create
    # NOTE: I'm referencing an :auto_analysis_rule parameter here because 
    # that's my desired param key name. It doesn't exist in the request
    # as shown here.
    render json: Rule.create(params[:auto_analysis_rule])
  end
end

我找不到任何提及 $http 从 URL 或任何 in the docs 推断根 JSON 密钥的内容。

"rule" 参数键来自哪里?

【问题讨论】:

    标签: ruby-on-rails json angularjs ruby-on-rails-4


    【解决方案1】:

    Rails 自动包装作为模型属性的参数。如果 one 是 Rule 模型的属性,则有效负载将如下所示:{"rule" =&gt; {"one" =&gt; "two"}}

    此功能无需包含所有属性的顶级键。换句话说,如果attr1attr2MyModel 模型中的字段,则以下负载将被视为相同:

    { "mymodel" : { "attr1" : "val1", "attr2" : "val2" } }
    
    { "attr1" : "val1", "attr2" : "val2" }
    

    可以在初始化程序中按控制器或应用程序范围禁用此功能。查看此答案以获取更多信息:Rails 3 params unwanted wrapping

    【讨论】:

    • 哇。我不知何故与 Rails 合作了大约 4 年,而我没有遇到这种情况。我想我从来没有尝试过弄乱我发送的 JSON 对象的根键,所以它总是透明地工作。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 2016-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多