Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if params[:some][:field] is nil?

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 ?

like image 590
deny7ko Avatar asked Aug 07 '12 12:08

deny7ko


3 Answers

 if params[:report] && params[:report][:start_date] && params[:report][:end_date]
like image 175
Mikhail Nikalyukin Avatar answered Oct 19 '22 01:10

Mikhail Nikalyukin


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
like image 12
steel Avatar answered Oct 19 '22 02:10

steel


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.

like image 7
Dan Tappin Avatar answered Oct 19 '22 00:10

Dan Tappin