Rails:同时发送两个强参数时如何出错?只允许其中之一

问题描述 投票:0回答:1

假设我在输入上接受两个不同的参数:

param1
param2
,但我不允许它们一起传递。在这种情况下我该如何出错?我需要通知客户他们发送的内容有误

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

谢谢

ruby-on-rails ruby validation parameters strong-parameters
1个回答
0
投票

允许它们两者并验证控制器中的逻辑怎么样?

  # 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
© www.soinside.com 2019 - 2024. All rights reserved.