158
135

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ネストするStrong Parametersの書きかた

Last updated at Posted at 2017-07-03

パラメータがネストするにしたがって、Strong Parametersの permit の書きかたがややこしくなっていくのでまとめました。

基本パターン

params
{
  "name": "Foo Bar",
  "email": "foo@example.com"
}
params.permit(:name, :email)

オブジェクトが1回ネストするパターン

params
{
  "name": "Foo Bar",
  "address": {
    "prefecture": "Kanagawa",
    "city": "Yokohama"
  }
}
params.permit(:name, address: [:prefecture, :city])

配列が1回ネストするパターン

params
{
  "name": "Foo Bar"
  "friends": [
    {
      "name": "Fizz Buzz"
    },
    {
      "name": "Lorem Ipsum"
    }
  ]
}
params.permit(:name, friends: [:name])

オブジェクトが1回ネストするパターンと同じになります。

2回ネストするパターン

params
{
  "name": "Foo Bar",
  "friends": [
    {
      "name": "Fizz Buzz",
      "address": {
        "prefecture": "Kanagawa",
        "city": "Yokohama",
      },
      "friends": [
        {
          "name": "Foo Bar"
        }
      ]
    },
    {
      "name": "Lorem Ipsum",
      "address": {
        "prefecture": "Kanagawa",
        "city": "Yokosuka",
      },
      "friends": [
        {
          "name": "Foo Bar"
        }
      ]
    }
  ]
}
params.permit(:name, { friends: [:name, { address: [:prefecture, :city], friends: [:name] }] })

参考

『Rubyのしくみ』("Ruby Under a Microscope") の著者のPat Shaughnessy氏が、Strong Parametersの覚えかたについて次のページで図を交えつつ解説しています。

To Permit a Hash, Pass an Array
To Permit an Array, Pass a Hash

Hashを許可したかったら配列を、配列を許可したかったらHashを渡せ、とのことです。

158
135
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
158
135

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?