環境
rails v5
どうした
railsのformでviewから取得した値をHash型にしたい。
paramsの型はActionController::Parametersという型でした。
pry(#<WelcomeController>)> @data
=> <ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"xxx", "data"=>{"version"=>"1"}, "commit"=>"submit", "controller"=>"welcome", "action"=>"index"} permitted: false>
これをHashにしたい。
to_hashメソッドを使えばいいようだが、許可された項目しかhashにできないもよう。
params.permit!.to_hashのようにすればHashに変換できる。
他のメソッド
ActionController::Parametersには他にもハッシュ関連のメソッドがありました。コメントをいただき調べてみました。
to_h
to_hメソッドはpermitされていない項目を除いたsafeなActiveSupport::HashWithIndifferentAccessクラスのデータを戻します。
参考先にはReturns a safe ActiveSupport::HashWithIndifferentAccessとありました。
safeというのは、permitしたものだけを戻すからsafeと形容されているようです。
to_hash
permitされていない項目を除いたsafeなHashクラスのデータを戻します。
to_unsafe_h
ActiveSupport::HashWithIndifferentAccessクラスのデータを戻します。メソッド名にあるとおり、unsefeすなわち、permitされていないデータも戻ります。
to_unsafe_hash
こちらがポイントなのですが、to_unsafe_hメソッドへのエイリアスです。
したがって、ActiveSupport::HashWithIndifferentAccessクラスを戻します。
今回はHash型がほしかったため、こちらはつかえないようです。
まとめる
対応関係が成り立っていないので紛らわしいです。
to_h => ActiveSupport::HashWithIndifferentAccess
to_hash => Hash
to_unsafe_h => ActiveSupport::HashWithIndifferentAccess
to_unsafe_hash => ActiveSupport::HashWithIndifferentAccess