0

How to achieve sth like if params[:filters][:company_name] is present (not nil) then do below actions but if it's nil - skip and do the rest of the code below/outside of this if ?

if params[:filters][:company_name]
  contains = Process
             .where(
               'company_name LIKE ?', "#{params[:filters][:company_name].downcase}%"
             )
end
mr_muscle
  • 2,536
  • 18
  • 61

2 Answers2

4

I'm assuming your problem is that the code "blows up" if params[:filters] is nil. (You get an error: "undefined method :[] for nil:NilClass".)

There are multiple ways to handle this, but probably the most concise is to use Hash#dig:

if params.dig(:filters, :company_name)
  # ...
end

This won't fail if params[:filters] == nil. From the above linked documentation (emphasis is mine):

Extracts the nested value specified by the sequence of key objects by calling dig at each step, returning nil if any intermediate step is nil.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
0

Try changing

if params[:filters][:company_name]

to

if params[:filters] && params[:filters][:company_name]
Mark
  • 6,112
  • 4
  • 21
  • 46