lostinthecloud lostinthecloud - 4 months ago 18
Ruby Question

Rails: Should exceptions raised due to missing params be rescued?

I'm pretty new to Ruby on Rails. I have a relatively straightforward question: Should exceptions raised due to missing params be rescued?

For example, imagine the following code in a FriendRequestsController:

...
def update
@request = FriendRequest.find(params[:id])

if @request.update(friend_request_params)
flash[:notice] = "Friend request updated successfully."
redirect_to current_user
else
flash[:errors] = @request.errors.full_messages
redirect_to current_user
end
end

private
def friend_request_params
params.require(:friend_request).permit(:status)
end
...


If the call to update on the model fails, the error message(s) will be stored in flash. But if there is something wrong with params such that an exception is raised in the friend_request_params helper method, the app will fail. Is it the convention to allow that? Is there a better way to do this?

Answer

In short the answer is no. When you call

  def friend_request_params
    params.require(:friend_request).permit(:status)
  end

You have established a contract with any action that uses the friend_request_params. If that action calls friend_request_params and doesn't send a :friend_request, the action has violated the contract and an exception should be raised. Your application is legitimately not working as designed and the exception is your canary in the coal mine so to speak.

Comments