如何测试rails中是否存在参数 [英] How to test if parameters exist in rails

查看:52
本文介绍了如何测试rails中是否存在参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Ruby on Rails 中使用 IF 语句来尝试测试是否设置了请求参数.无论是否设置了两个参数,都会触发以下 if 块的第一部分.如果 params[:one] 和 params[:two] 都设置了,我怎样才能让这部分只被触发?

I'm using an IF statement in Ruby on Rails to try and test if request parameters are set. Regardless of whether or not both parameters are set, the first part of the following if block gets triggered. How can I make this part ONLY get triggered if both params[:one] and params[:two] is set?

if (defined? params[:one]) && (defined? params[:two])
 ... do something ...
elsif (defined? params[:one])
 ... do something ...
end

推荐答案

你想要 has_key?:

if(params.has_key?(:one) && params.has_key?(:two))

只要检查 if(params[:one]) 就会被there but nil"和there but false"的值所迷惑,而您正在询问是否存在.您可能需要区分:

Just checking if(params[:one]) will get fooled by a "there but nil" and "there but false" value and you're asking about existence. You might need to differentiate:

  • 根本没有.
  • 有但nil.
  • 有但false.
  • 只有一个空字符串.

也是.如果没有关于您的确切情况的更多细节,就很难说.

as well. Hard to say without more details of your precise situation.

这篇关于如何测试rails中是否存在参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆