Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if parameters exist in rails

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 
like image 525
Darren Avatar asked Apr 12 '11 01:04

Darren


People also ask

How to check if a value exists in a hash Ruby?

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 .

How to check if key has value Ruby?

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.

What is strong parameters in Rails?

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.

Has value in Ruby?

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.


2 Answers

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.

like image 101
mu is too short Avatar answered Sep 22 '22 18:09

mu is too short


I am a fan of

params[:one].present?

Just because it keeps the params[sym] form so it's easier to read.

like image 42
netricate Avatar answered Sep 18 '22 18:09

netricate