require_params ensures that parameters that your API actions require are present.
Include RequireParams to your ApplicationController:
class ApplicationController < ActionController::API
include RequireParams
endUse the require_params class method in your controllers to specify which parameters are required for which actions:
class UsersController < ApplicationController
require_params [:username, :email, :password], only: :create
def create
# Do important stuff here
end
endrequire_params can be called multiple times for each actions:
class UsersController < ApplicationController
require_params [:username, :password]
require_params [:email], only: :create
# Equivalent to calling
# require_params [:username, :password, :email], only: :create
# require_params [:username, :password], except: :create
def create
# Make a new user
end
def sign_in
# Signs in user
end
endIf any one of the required parameters is missing, your action handler will not be called at all. Instead, an error hash that looks like this will be served with 400 Bad Request:
{
errors: {
username: ["is missing"],
password: ["is missing"]
}
}require_params is backed by prepend_before_action. As a result, it can be guaranteed that by the time your before_action hooks and actions are executed, the required parameters are present.
Add this line to your application's Gemfile:
gem 'require_params'And then execute:
$ bundleOr install it yourself as:
$ gem install require_paramsInclude RequireParams to your controllers:
class ApplicationController < ActionController::API
include RequireParams
endThe gem is available as open source under the terms of the MIT License.