はじめに
paramsの値の取得方法について試した結果をまとめます。
paramsとは
- ActionController::Parametersクラスのインスタンス
- Hashクラスは継承していない
paramsの値を取得する
-
{"[キー名]" => "[値]"}
の形で格納される
取得結果の例
下記の出力結果はすべて、Rails.loggerの出力結果に改行などの編集を加えています。
- AuthorモデルにBooksモデルが親子関係にあり、フォームで同時に保存する場合のパラメータを想定
- author_paramsは下記のようにストロングパラメータとして取得する場合
def author_params
params.require(:author).permit(:last_name, :first_name, books_attributes: [:book_name])
end
params
{"authenticity_token"=>"[トークン]",
"author"=>{
"last_name"=>"山田", "first_name"=>"花子",
"books_attributes"=>{
"0"=>{"id"=>"", "book_name"=>"きょう"},
"1"=>{"id"=>"", "book_name"=>"あした"}}},
"controller"=>"mm/authors",
"action"=>"create"}
author_params
{"first_name"=>"花子",
"last_name"=>"山田",
"books_attributes"=>#<ActionController::Parameters {
"0"=>#<ActionController::Parameters {"id"=>"", "book_name"=>"きょう"} permitted: true>,
"1"=>#<ActionController::Parameters {"id"=>"", "book_name"=>"あした"} permitted: true>}
permitted: true>}
params[:author][:first_name] / params.dig(:author, :first_name) / author_params[:first_name] / author_params.dig(:first_name)
花子
キー名はシンボルでも文字列でも指定できるのでparams['author']['first_name']
でも取得できる
params[:author][:books_attributes] / params.dig(:author, :books_attributes)
{"0"=>{"id"=>"", "book_name"=>"きょう"},"1"=>{{"id"=>"", "book_name"=>"あした"}}
author_params[:books_attributes] / author_params.dig(:books_attributes)
{"0"=>#<ActionController::Parameters {"id"=>"", "book_name"=>"きょう"} permitted: true>,
"1"=>#<ActionController::Parameters {"id"=>"", "book_name"=>"あした"} permitted: true>}
params[:author][:books_attributes]['0'] / params.dig(:author, :books_attributes, '0') / author_params[:books_attributes]['0'] / author_params.dig(:books_attributes, '0')
インデックスの数字に[0]
[:0]
は使えない
{"0"=>{"id"=>"", "book_name"=>"きょう"}
params[:author][:books_attributes]['0'][:book_name] / params.dig(:author, :books_attributes, '0', :book_name) / author_params[:books_attributes]['0'][:book_name] / author_params.dig(:books_attributes, '0', :book_name)
きょう