0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsのfetch関数について

Posted at

背景

  • ストロングパラメータをいじいじする時に使う関数でfetchがあるがこの関数が第二引数ありとブロック引数ありの時の挙動が違ったのでここに記す

前提条件

  • params = {}

第二引数がある時

  • :hogeキーが見つからなかった時、第二引数に定義した値を返す
params.fetch(:hoge, []) #=> []
params.fetch(:hoge, "") #=> ""
ハッシュの時はストロングパラメータを返しているっぽい
params.fetch(:hoge, {}) #=> #<ActionController::Parameters {} permitted: false>

ブロック引数がある時

  • :hogeキーが見つからなくても、ブロックが実行されてしまいます
params.fetch(:hoge, []) {|h| h.permit(:fugo)} #=> error
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?