LoginSignup
20
15

More than 5 years have passed since last update.

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

Posted at

はじめに

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
20
15
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
20
15