Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What is going on with this article?
@y-sugasawa

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

More than 5 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
12
Help us understand the problem. What is going on with this article?
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.
Sign Up
If you already have a Qiita account Login
12
Help us understand the problem. What is going on with this article?