Search code examples
ruby-on-railsransack

Ransack causing issues with other queries on the model


I'm trying to implement Ransack gem. I think I have the gem working, but my issue is with other queries on the same model. For example, I have a simple <%= @roasts.count %> on the total number of roasts on my index page. But I get the error undefined method 'count' for nil:NilClass when I submit the search query (http://localhost:3000/roasts?utf8=%E2%9C%93&q%5Bname_cont%5D=firefox&commit=Search). I'm 90% sure it's due to how I've got the queries set up under the if-else statement, but I can't work out the correct setup.

controller/roast_controller.rb

class RoastsController < ApplicationController
  before_action :set_roast, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:create, :edit, :update, :destroy]
  before_action :set_search

  def index
    if params[:q]
      @q = Roast.ransack(params[:q])
      @roastsalpha = @q.result.order(:name)
    else
      @roasts = Roast.all
    end
      @roastsalpha = Roast.order(:name)
      @roastsdesc = Roast.all.order("created_at DESC")
      @mostpopularroast = Roast.group(:country).select(:country).order("count(*) desc").first
      @mostpopularblend = Roast.group(:bestfor).select(:bestfor).order("count(*) DESC").first
      @countroastschart = Roast.order("roaster DESC").all
  end

Solution

  • Take a look at your Index action:

    def index
        if params[:q]
          @q = Roast.ransack(params[:q])
          @roastsalpha = @q.result.order(:name)
        else
          @roasts = Roast.all
        end
    

    You are receiving your error because @roasts is nil. If I am correct in my assumptions that your set_search action is doing something like @search = Roast.ransack(params[:q]) then this is being called before every action and setting params[:q]. So if we look at your if statement; params[:q] will always be true and @roasts will never be set. I think that to resolve this, you should remove the if-else statement.