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

j2cgzkjk  于 5个月前  发布在  Ruby
关注(0)|答案(2)|浏览(82)

假设我在输入端接受两个不同的参数:param1param2,但我不允许它们一起传递。在这种情况下,我如何出错?我需要通知客户端他们发送了错误的东西

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

字符串
谢谢

xzv2uavs

xzv2uavs1#

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

# 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

字符串

qij5mzcb

qij5mzcb2#

我会这样做。这将允许:params1,如果它存在于参数中,否则:param2

def key_params
  required_params = params.require(:key)

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

  required_params.permit(:other_params, attribute)
end

字符串

相关问题