0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Railsのstrong parametersでJSONを受け取る方法

Posted at

発生した問題

Rails の API でネストした JSON を受け取る際、strong parameters の設定が原因で unpermitted parameters エラーが発生。フロントエンドから送信した JSON が正しくパースされず、DB へ保存できなかった。

テーブル定義

JSON 型のカラムを持つテーブルの migration. MySQL.

create_table :xxx do |t|
  t.json :xxx
  t.timestamps
end

Controller の実装例(エラー発生時)

strong parameters の設定が原因でエラー発生。以下のコードでは、ネストした JSON 内のキーが許可されず unpermitted parameters エラーとなる。

class XxxController < ApplicationController

  # create アクションなど

  private

  def xxx_params
    params.require(:xxx).permit(:a_json_type)
  end
end

フロントエンドの送信例

axios を使い、ネストした JSON を送信。

axios.post('/xxx', {
  xxx: {
    a_json_type: {
      b_inside: 1,
      c_inside: 2
    }
  }
}, {
  headers: {
    'Content-Type': 'application/json'
  }
})

解決策

strong parameters でネストしたオブジェクトを許可するため、キーをハッシュとして指定する必要あり。下記のコードに修正。

class XxxController < ApplicationController

  # create アクションなど

  private

  def xxx_params
    params.require(:xxx).permit(a_json_type: {})
  end
end

この修正により、ネストした JSON 内のキーが正しく許可され、DB へ正常に値が保存可能。DB 側で JSON 型を利用することで、JSON のパース処理を自前で実装する手間が省ける。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?