ruby-on-railsjsonrubypg-search

why no implicit conversion of nil into Hash?


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


Solution

  • 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