我使用以下请求有效负载执行POST http://0.0.0.0:3000/clients
:
{"name": "David Smith", "email": "david@site.com"}
Firefox和Chrome都清楚地表明这是有效载荷。
但是,在Rails日志中,我看到了:
在2014-01-05 20:59:52 +1100开始发布“/ api / clients”for 127.0.0.1 由ClientsController处理#create as HTML 参数:{“name”=>“David Smith”,“email”=>“david@site.com”,“client”=> {“name”=>“David Smith”,“email”= > “中david@site.com”}}
的确,如果我在params
打印ClientsController#create
,我会看到它包含密钥client
。
"client"=>{"name"=>"David Smith", "email"=>"david@site.com"}
部分如何成为params
的一部分?为什么Rails会弄乱params
?
我使用Rails 4.0.2。
使用AngularJS发出请求:
ClientsNewCtrl = ['$scope', '$http', '$q', ($scope, $http, $q) ->
$scope.client =
name: ''
email: ''
$scope.createNewClient = ->
defer = $q.defer()
$http.post('/api/clients', $scope.client).success ->
console.log 'Success!'
defer.resolve()
.error (errors, status) ->
errors = ["Couldn't create the client."] if status != 422
console.log errors
defer.reject(errors)
defer.promise
]
以下是我为展示问题而创建的示例:https://github.com/moroshko/rails-params
rails s
http://0.0.0.0:3000
params
是否有额外的client
密钥答案 0 :(得分:1)
确实,Rails在params
默认情况下指定请求config/initializers/wrap_parameters.rb
。
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
要停止此行为,可以执行以下操作:
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [] if respond_to?(:wrap_parameters)
end
相关信息: