2

我做POST http://0.0.0.0:3000/clients與下列請求負載:爲什麼Rails搞亂params?

{"name": "David Smith", "email": "[email protected]"} 

兩個Firefox和Chrome清楚地表明,這是有效載荷。

但是,在Rails的日誌中我看到:

開始POST 「/ API /客戶」 爲127.0.0.1,在2014年1月5日20點59分52秒1100 處理由ClientsController#創建作爲HTML 參數:{「name」=>「David Smith」,「email」=>「[email protected]」,「client」=> {「name」=>「David Smith」,「email」=> 「[email protected]」}}

事實上,如果我在ClientsController#create打印出來params,我看到它包含的關鍵client

"client"=>{"name"=>"David Smith", "email"=>"[email protected]"}零件如何成爲params的一部分?爲什麼Rails搞亂params

我使用Rails 4.0.2。

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

  1. rails s
  2. 轉到http://0.0.0.0:3000


    請求使用AngularJS製成

  3. 打開瀏覽器的控制檯來觀察請求
  4. 輸入姓名,電子郵件,並點擊創建
  5. 退房的Rails日誌看到params有多餘的client關鍵
+0

你是如何創造這些PARAMS?表單還是直接在URL中? –

+0

我認爲rails具有自動包裝JSON請求參數的功能,但你的看起來像它的HTML,所以這不應該成爲一個問題。你是否通過瀏覽器提交表單?您是否通過開發人員控制檯查看了請求主體? – phoet

+0

我從來沒有遇到Rails以任何方式搞亂params。我從你的SO配置文件中看到你對Rails有經驗,但仍然希望這是你的錯誤。你使用強參數,你參考的代碼是在過濾之前還是之後?表單/請求的外觀如何? –

回答

1

事實上,導軌和要求params搞亂如在config/initializers/wrap_parameters.rb中默認指定:

ActiveSupport.on_load(:action_controller) do 
    wrap_parameters format: [:json] if respond_to?(:wrap_parameters) 
end 

T O停止這種行爲,一個可以這樣做:

ActiveSupport.on_load(:action_controller) do 
    wrap_parameters format: [] if respond_to?(:wrap_parameters) 
end 

相關信息: