Why not login to Qiita and try out its useful features?

We'll deliver articles that match you.

You can read useful information later.

29
31

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.

StrongParameters で配列の中身のパラメータチェック

Last updated at Posted at 2014-10-15

Rails4 の StrongParameters で配列の中身までのパラメータチェックしたかったのですが、

params.permit(:users => [])

上記の様に、permit 内で、配列かのチェック方法しか見つけられず、
自分でコンソールを使って色々試した結果を、備忘録として残します。

やりたいこと

下記のような、JSON リクエストで、StrongParameters の require を使用して、配列の中身のパラメータまでチェックしたい

{
  "users": [
    { "role": "admin", "name": "taro" },
    { "role": "user", "name": "hanako" },
    { "role": "user", "name": "jiro" },
    { "role": "user", "name": "saburo" },
  ]
}

Rails コンソールで実行

コンソールで、パラメータを作成し、チェック

console » users = {
        »   users: [
        »     { role: 'admin', name: 'taro' },
        »     { role: 'user', name: 'hanako' },
        »     { role: 'user', name: 'jiro' },
        »     { role: 'user', name: 'saburo' },
        »   ]
        » }

console » parameters = ActionController::Parameters.new(users)
console » parameters.require(:users).map { |u| u.permit(:role, :name) }
=> [
  [0] {
    "role" => "admin",
    "name" => "taro"
  },
  [1] {
    "role" => "user",
    "name" => "hanako"
  },
  [2] {
    "role" => "user",
    "name" => "jiro"
  },
  [3] {
    "role" => "user",
    "name" => "saburo"
  }
]

role が必要ない場合は、下記のようにする

console » parameters.require(:users).map { |u| u.permit(:role) }
=> [
  [0] {
    "role" => "admin"
  },
  [1] {
    "role" => "user"
  },
  [2] {
    "role" => "user"
  },
  [3] {
    "role" => "user"
  }

Controller での記載

Controller には下記のように記載すれば、各アクションで使用できる

private
def users_params
  params.require(:users).map { |u| u.permit(:role, :name) }
end

使用方法

User.create(users_params)
29
31
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

Qiita Advent Calendar is held!

Qiita Advent Calendar is an article posting event where you post articles by filling a calendar 🎅

Some calendars come with gifts and some gifts are drawn from all calendars 👀

Please tie the article to your calendar and let's enjoy Christmas together!

29
31

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?