ruby-on-railsrubyruby-grape

Ruby don't do actions for nil class in if block


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

Solution

  • 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.