10

I tried code, that plused a lot of people - How to test if parameters exist in rails, but it didn't work():

     if ( params.has_key?([:start_date]) && params.has_key?([:end_date]) )

I think, that is because of complicated params and if I write this:

       if ( params.has_key?([:report][:start_date]) && params.has_key?([:report][:end_date]) )

gives me error

        can't convert Symbol into Integer

this doesn't work too:

           if ( params[:report][:start_date] && params[:report][:end_date] )

gives me error:

        undefined method `[]' for nil:NilClass

It always go into else statement.

Here are my params:

    report: 
    start_date: 01/08/2012
    end_date: 10/08/2012

Can someone help me ?

Community
  • 1
  • 1
Denys Medynskyi
  • 2,353
  • 8
  • 39
  • 70
  • Possible duplicate of [How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?](http://stackoverflow.com/questions/4371716/how-to-avoid-nomethoderror-for-missing-elements-in-nested-hashes-without-repeat) – user513951 Jan 06 '16 at 05:22

5 Answers5

13
 if params[:report] && params[:report][:start_date] && params[:report][:end_date]
Mikhail Nikalyukin
  • 11,867
  • 1
  • 46
  • 70
12

Cross-post answer from here:

Ruby 2.3.0 makes this very easy to do with #dig.

h = { foo: {bar: {baz: 1}}}

h.dig(:foo, :bar, :baz)           #=> 1
h.dig(:foo, :zot, :baz)           #=> nil
Community
  • 1
  • 1
steel
  • 11,883
  • 7
  • 72
  • 109
7

I have been looking for a better solution too. I found this one:

Is there a clean way to avoid calling a method on nil in a nested params hash?

params[:some].try(:[], :field)

You get the value or nil if it does not exist.

So I figured let's use try a different way:

params[:some].try(:has_key?, :field)

It's not bad. You get nil vs. false if it's not set. You also get true if the param is set to nil.

Community
  • 1
  • 1
Dan Tappin
  • 2,692
  • 3
  • 37
  • 77
6

It would seem you need the following

    params[:report].present?

or

    params[:report].nil?

or

    params[:report].empty?

depending on what you are trying to check for

Purple Hexagon
  • 3,538
  • 2
  • 24
  • 45
1

This works to:

if params[:report].has_key?(:start_date)

And maybe add this so you also check if it is not empty:

&& !params[:report][:start_date].empty?