why no implicit conversion of nil into Hash?

1.7k views Asked by At

after setup a search into a serializer! Rails spits out

no implicit conversion of nil into Hash

So, please someone can point out whats wrong with this code?

class SearchController < ApplicationController
  def results
    results_query = PgSearch.multisearch(params[:q]).paginate(page: page, per_page: 20)
    result = results_query.map(&:searchable).map do |result_item|
      case result_item.class.name
      when 'Post'
        PostSerializer.new(result_item)
 
      else
        raise NotImplementedError
      end
    end

    render json: {
      items: result,
      page: page,
      pages: results_query.total_pages
    }
  end

  def page
    params[:page] || 1
  end

  def serialize(data, serializer)
    ActiveModel::Serializer::CollectionSerializer.new(data, each_serializer: serializer)
  end
end

enter image description here

enter image description here

3

There are 3 answers

0
mee_yuhh On BEST ANSWER

Since your case statement isn't checking many values, you could always make it into a standard if/else statement:

if result_item && result.class.name == 'Post'
    PostSerializer.new(result_item)
else
    raise NotImplementedError
end
0
Clemens Kofler On

Based on the screenshot you've provided, I've quickly checked the source code. The offending line seems to be this one: https://github.com/Casecommons/pg_search/blob/master/lib/pg_search/document.rb#L22. The only reason why this would raise the described TypeError is if PgSearch.multisearch_options is nil – which, as far as I understand the code, would only be possible if you accidentally overwrote it in a wrong way. So I'd suggest doublechecking your global setup for PgSearch.multisearch_options to make sure this is actually set.

The east way to check the setting is by using a debugger or putting something like puts PgSearch.multisearch_options or Rails.logger.info 'PgSearch.multisearch_options' into the controller directly above the call that's failing.

0
b0rdjack On

Well, on the screenshots you've provided we can see the log message specifies that the error is on line 5.

According to your code, line 5 is: case result_item.class.name

The error message is TypeError (no implicit conversion of nil into Hash).

You're trying to get the class then the name of result_item. So the problem is with result_item which is equal to nil.

In order the resolve your problem you might want to check the ouput of results_query.map(&:searchable).map.