How To Get Raw Post Parameters In Rails

Posted By Weston Ganger

Its surprisingly difficult to get the raw POST parameters from a Rails request. Rails normally adds some parameters and performs some magic mapping. This means that the params hash is not exactly the same as the actual provided request parameters.

Here are a few different ways to retrieve the parameters within a controller:

  • params
    • Fully enhanced by Rails
    • Request parameters are merged with URL parameters, with request parameters taking precedence
    • Adds additional keys like controller, action, etc
  • request.url_parameters
    • Only returns url parameters, request and path parameters are excluded
  • request.request_parameters
    • Only returns request parameters, url and path parameters are excluded
    • Will also duplicate your post parameters into a new parameter based on your controller name
    • Example for Api::V1::PostsController
      • Input: { name: "foo", active: true, code: "AAA" }
      • Output: `{ name: "foo", active: true, code: "AAA", post: { name: "foo", active: true, code: "AAA" }
  • request.path_parameters
    • Only returns Rails router path paramters such as :controller, :action, :id, :parent_id etc.
  • request.raw_post and request.env["RAW_POST_DATA"]
    • Completely original un-modified and un-parsed POST data
    • You have to manually parse it: JSON.parse(request.raw_post).with_indifferent_access

The solution for my situation was to use request.raw_post. So I added a helper method to the controller.

class ApplicationController < ActionController::Base

  def raw_params
    @raw_params ||= JSON.parse(request.raw_post).with_indifferent_access

  helper_method :raw_params ### to access within views


Article Topic:Software Development - Ruby / Rails

Date:November 17, 2021