Checking for values in a Rails params hash is complicated. In this post we will use the #fetch method to ensure nil is not called on a params hash.
1 2 3 |
|
The code above will call #present? on nil if params[:search][:organization_id] does not exist.
A better way to write the conditional:
1 2 3 |
|
Writing a similar conditional with #fetch:
1 2 3 |
|
Let’s break this method down into simpler components:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
I like the ability to call #fetch with a default return value if one does not exist. This leads to better ways to handle nil or catch errors.