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

RailsにJSONパラメータを送った際のwrap_parametersについて

More than 3 years have passed since last update.

はじめに

Railsのwrap_parametersについてちょっと調べたのでメモ。

普通のパラメータ

Railsでは以下のようにパラメータを送ると、一塊のハッシュにしてくれる。
※paramsは正確にはハッシュのサブクラスらしいです

Content-Type: application/x-www-form-urlencoded

user[id]: 1
user[name]: y-sugasawa
user[hobby_id][]: 100
user[hobby_id][]: 200
users_controller.rb
class UsersController < ApplicationController
  def index
    p params[:user] # {id: 1, name: "y-sugasawa", hobby_id: [100, 200]}
  end
end

wrap_parameters

パラメータがJSON形式の時は、パラメータのkeyから「user」の部分を取り除けます。
キーの「user」というのはcontrollerの名前から自動的に決定されます。

Content-Type: application/json
{
  "id": 1,
  "name": "y-sugasawa",
  "hobby_id": [100, 200]
}
users_controller.rb
class UsersController < ApplicationController
  def index
    p params[:user] # {id: 1, name: "y-sugasawa", hobby_id: [100, 200]}
  end
end

注意点

上記のjsonの例で、以下のようなUserモデルがあった場合

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t:string :name
      t.timestamp null: false
    end
  end
end

users_controllerは自動的にUserモデルのためのパラメータと解釈してUserモデルに存在しないカラムは除外されてしまう

users_controller.rb
class UsersController < ApplicationController
  def index
    p params[:user] # {id: 1, name: "y-sugasawa"}  hobby_idが除外されている
    p params[:hobby_id] # [100, 200]
  end
end

これを回避する場合は以下のように記述する

users_controller.rb
class UsersController < ApplicationController

  wrap_parameters :user, include: [:name, :hobby_id]

  def index
    p params[:user] # {id: 1, name: "y-sugasawa", hobby_id: [100, 200]}
  end
end
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
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