0

I am trying to use two if statements within my index. The first allows the user to view by tags, and the second defines the Kaminari pagination gem, gem 'kaminari'.

The problem is, I can't get both to work. With the code as is below, the pagination works, but filtering by tag does not. If I comment out the pagination, the the tags work.

I'm fairly sure I don't have the correct logic around the two if statements, but I can't work out how to right this.

class CoffeeshopsController < ApplicationController


  def index
    if params[:tag]
      @coffeeshops = Coffeeshop.tagged_with(params[:tag])
    else
      @coffeeshops = Coffeeshop.all.order("created_at DESC").page params[:page]
    end

    if params[:term]
      @coffeeshops = Coffeeshop.search_by_full_name(params[:term])
    else
      @coffeeshops = Coffeeshop.all.order("created_at DESC").page params[:page]
    end
  end
Simon Cooper
  • 1,574
  • 4
  • 24
  • 53

2 Answers2

1

You are overwriting @coffeshops in the second if block. Having said that, you should put the pagination after all filtering.

  def index
    @coffeeshops = Coffeeshop.all
    if params[:tag]
      @coffeeshops = @coffeeshops.tagged_with(params[:tag])
    end
    if params[:term]
      @coffeeshops = @coffeeshops.search_by_full_name(params[:term])
    end
    # paginate
  end
Thomas R. Koll
  • 3,131
  • 1
  • 19
  • 26
  • ok, makes sense. I now however get `undefined method `total_pages'` on calling `<%= paginate @coffeeshop %>` in my view, but that might be more specific to Kaminari. – Simon Cooper Apr 29 '17 at 16:25
0

Solved it with the below. Thanks to another SO question.

def index
  if params[:tag]
    @coffeeshops = Coffeeshop.tagged_with(params[:tag])
  else
    @coffeeshops = Coffeeshop.all
  end
  @coffeeshops = @coffeeshops.order("created_at DESC").page params[:page]
end

Important point I've also taken out the search term statement for now.

Thomas R. Koll
  • 3,131
  • 1
  • 19
  • 26
Simon Cooper
  • 1,574
  • 4
  • 24
  • 53