Skip to content

Instantly share code, notes, and snippets.

@joost
Last active July 31, 2018 06:38
Show Gist options
  • Save joost/166199c7c7d0f04c3204 to your computer and use it in GitHub Desktop.
Save joost/166199c7c7d0f04c3204 to your computer and use it in GitHub Desktop.
Validate parameters in Rails 4 JSON API
class ApiController < ApplicationController
# FIXME: Since we cannot set ActionController::Parameters.action_on_unpermitted_parameters = :raise
# on a controller level we do this hotfix.
class ApiParameters < ActionController::Parameters
def action_on_unpermitted_parameters
:raise
end
end
def params
@_params ||= ApiParameters.new(request.params)
end
# Handling of invalid parameters
rescue_from(ActionController::ParameterMissing) do |exception|
render json: { message: exception.message, params: [exception.param] }, status: :bad_request
end
rescue_from(ActionController::UnpermittedParameters) do |exception|
render json: { message: exception.message, params: exception.params }, status: :bad_request # { unknown_parameters: exception.params }
end
skip_before_action :verify_authenticity_token
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment