How to test if parameters exist in rails
Solution 1:
You want has_key?
:
if(params.has_key?(:one) && params.has_key?(:two))
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:
- Not there at all.
- There but
nil
. - There but
false
. - There but an empty string.
as well. Hard to say without more details of your precise situation.
Solution 2:
I am a fan of
params[:one].present?
Just because it keeps the params[sym]
form so it's easier to read.
Solution 3:
use blank? http://api.rubyonrails.org/classes/Object.html#method-i-blank-3F
unless params[:one].blank? && params[:two].blank?
will return true if its empty or nil
also... that will not work if you are testing boolean values.. since
>> false.blank?
=> true
in that case you could use
unless params[:one].to_s.blank? && params[:two].to_s.blank?
Solution 4:
You can write it more succinctly like the following:
required = [:one, :two, :three]
if required.all? {|k| params.has_key? k}
# here you know params has all the keys defined in required array
else
...
end