Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle required parameters in Rails controllers?

What is the best way to check if are necessary params are being passed to the application? And what is the best way to respond to the client indicating the errors in a json response?

like image 807
ciaoben Avatar asked Dec 02 '25 15:12

ciaoben


1 Answers

Use Strong Parameters: https://github.com/rails/strong_parameters

Straight from the github page:

"If you want to make sure that multiple keys are present in a params hash, you can call the method twice:"

params.require(:token)
params.require(:post).permit(:title)

Then, from the documentation again:

"... config.action_controller.action_on_unpermitted_parameters property in your environment files. If set to :log the unpermitted attributes will be logged, if set to :raise an exception will be raised."

To handle the exception, you can add this to the application controller:

rescue_from 'ActionController::ParameterMissing' do |exception|
  render json: { errors: exception.to_s }.to_json, status: 422
end
like image 73
Tom Fast Avatar answered Dec 04 '25 06:12

Tom Fast



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!