Rails: How to error when two strong parameters are sent together at the same time? Allow one of them only

46 Views Asked by At

Let's say I accept two different parameters on input: param1 and param2 but I don't allow them to be passed together. How do I error in that case? I need to notify the client they are sending something wrong

params.require(:key).permit(
:other_param,
:param1 || :param2).to_hash

Thanks

2

There are 2 best solutions below

0
tonystrawberry On

What about allowing them both and validates your logic in your controller?

  # When `param1` and `param2` are sent at the same time, 
  # a 400 - Invalid Request will be sent back to the client
  def hello
    hello_params = params.require(:key).permit(:param1, :param2)

    # Return 400 - Invalid Request if both params are present
    if hello_params[:param1] && hello_params[:param2]
      render json: { message: "Both param1 and param2 should not be sent together." }, status: 400
      return
    end

    render json: { message: "Hello, world!" }
  end
0
spickermann On

I would do it like this. This will permit :params1 if it is present in the params, :param2 otherwise.

def key_params
  required_params = params.require(:key)

  attribute = required_params.key?(:param1) ? :params1 : :params2

  required_params.permit(:other_params, attribute)
end