marcamillion
marcamillion

Reputation: 33755

How to check for the presence of no value in a "params[:attribute]"

When I have a an array like this:

[5] pry(#<HomeController>)> params["search"]["sources"] => [""]

How do I check that instance to be true?

I tried the following, but it fails:

[8] pry(#<HomeController>)> params[:search][:sources].empty?
=> false
[9] pry(#<HomeController>)> params[:search][:sources].nil?
=> false
[3] pry(#<HomeController>)> params["search"]["sources"].empty?
=> false
[4] pry(#<HomeController>)> params["search"]["sources"].eql? ""
=> false
[10] pry(#<HomeController>)> params[:search][:sources].blank?
=> false
[11] pry(#<HomeController>)> params[:search][:sources].any?
=> true

Whenever the value of an attribute of my params is empty, or equal to "", I want to do something specific.

I would like it to be the conditional of an if statement, so it has to return true in the above case.

Here is the actual full params I am checking:

 params
=> <ActionController::Parameters {"search"=><ActionController::Parameters {"keywords"=>"", "types"=>[""], "categories"=>["", "", "", "", "", "", "", "Hockey", "", "", "", "", "", "", "", "", "", "", "", "", ""], "date_from"=>"", "date_to"=>"", "sources"=>[""], "genders"=>[""], "ages"=>[""]} permitted: false>, "controller"=>"home", "action"=>"index"} permitted: false>

Basically I want to check to see if any of the values in params[:search][:categories] is not empty. In the above case, we see that one of the values is equal to the string Hockey, so in this case it should return false.

Upvotes: 0

Views: 50

Answers (2)

Jonathan
Jonathan

Reputation: 39

params[:search][:sources].all?(&:blank?)

Upvotes: 0

spickermann
spickermann

Reputation: 106842

I would probably try to avoid having to check for both – a blank array or an array including only an empty string. But if I had to I would to it explicit:

array = params[:search][:sources]
array.blank? || array == ['']

Another option might be:

params[:search][:sources].first.blank?

But I think the second option is harder to understand (at least all cases in which it would return true).

For the categories the condition would be:

params[:search][:categories].any?(&:present?)

Upvotes: 2

Related Questions