跳轉至內容 跳轉至搜尋

Action Controller Params Wrapper

將參數雜湊包裝成一個巢狀雜湊。這將允許客戶端提交要求,而不需要指定任何根元素。

這個功能在 JSON 中預設啟用,並可透過設定格式陣列進行自訂。

class ApplicationController < ActionController::Base
  wrap_parameters format: [:json, :xml]
end

你也可以針對特定控制器開啟它

class UsersController < ApplicationController
  wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form]
end

如果你針對 :json 格式啟用 ParamsWrapper,而非像這樣傳送 JSON 參數

{"user": {"name": "Konata"}}

你可以像這樣傳送參數

{"name": "Konata"}

它將包裝成一個巢狀雜湊,其中金鑰名稱與控制器的名稱相符。例如,如果你正在張貼到 UsersController,你的新 params 雜湊會像這樣顯示

{"name" => "Konata", "user" => {"name" => "Konata"}}

你還可以指定參數應包裝成的金鑰,以及使用 :include:exclude 選項包裝的屬性清單,如下所示

class UsersController < ApplicationController
  wrap_parameters :person, include: [:username, :password]
end

對於未設定 :include:exclude 選項的 Active Record 模型,它只會包裝類別方法 attribute_names 所傳回的參數。

如果你打算將參數傳遞到 ActiveModel 物件 (例如 User.new(params[:user])),你可以考慮將模型類別傳遞給方法。ParamsWrapper 將實際嘗試從模型中判斷屬性名稱清單,並僅包裝那些屬性

class UsersController < ApplicationController
  wrap_parameters Person
end

你仍可以傳遞 :include:exclude 來設定要包裝的屬性清單。

預設情況下,如果你未指定參數應包裝成的金鑰,ParamsWrapper 將實際嘗試判斷是否與其相關的模型。例如,這個控制器

class Admin::UsersController < ApplicationController
end

將嘗試檢查 Admin::UserUser 模型是否存在,並分別使用它來判斷包裝器金鑰。如果這兩個模型都不存在,它將退而使用 user 作為金鑰。

要針對控制器停用此功能

class UsersController < ApplicationController
  wrap_parameters false
end
命名空間

常數

EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8)