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
A particular value can be checked to see if it exists in a certain hash by using the has_value?() method. This method returns true if such a value exists, otherwise false .
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.
In Ruby, a hash is a collection of key-value pairs. A hash is denoted by a set of curly braces ( {} ) which contains key-value pairs separated by commas. Each value is assigned to a key using a hash rocket ( => ). Calling the hash followed by a key name within brackets grabs the value associated with that key.
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:
nil
.false
.as well. Hard to say without more details of your precise situation.
I am a fan of
params[:one].present?
Just because it keeps the params[sym]
form so it's easier to read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With