Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

パラメータがネストするにしたがって、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を渡せ、とのことです。

pepabo
「いるだけで成長できる環境」を標榜し、エンジニアが楽しく開発できるWebサービス企業を目指しています。
https://pepabo.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした