LoginSignup
58
31

More than 5 years have passed since last update.

ActionController::ParametersをHashにする

Last updated at Posted at 2018-09-15

環境

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

もっとくわしく!

ActionController::Parameters.to_hash

58
31
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
31