0

I am trying to paginate using kaminari on my rails app. On the first page i want to show 11 products and in all other pages i want to show 12 products. I followed the instructions on this post but get the following error:

undefined local variable or method `params' for #<Product::ActiveRecord_AssociationRelation:0x007fcef461e908>

See below for the show method being used:

@page = (params[:page]).to_i

if @page == 1
  @products = Store.find(params[:id]).products.order(sort_column + ' ' + sort_direction).limit(11)
else
  @products = Store.find(params[:id]).products.order(sort_column + ' ' + sort_direction).limit(12).offset(@page*12-13)
end

@products.instance_eval <<-EVAL
  def current_page
    #{@page}
  end
  def total_pages
    ((Store.find(params[:id]).products.all.count+1)/12.0).ceil
  end
EVAL

The error is generated in the store#show in the following line of code:

  <%= paginate @products %>
Community
  • 1
  • 1
Chinsky
  • 55
  • 9
  • 1
    no, the problem is coming from calling `params[:id]` in your instance_eval. What on earth are you trying to do there, why are you reinventing Kaminari's pagination? – sevenseacat Sep 08 '15 at 02:34
  • You were right, the error is coming from params[:id] in the intance_eval. How can i access the store's products inside the instance_eval? Thanks for your help – Chinsky Sep 08 '15 at 02:54

1 Answers1

0

I was able to hack it the error by creating a class variable outside the instance_eval and then calling it. see code below.

 @page = (params[:page] || '1').to_i

@@total_pages = ((Store.find(params[:id]).products.all.count+1)/12.0).ceil

if @page == 1
  @products = Store.find(params[:id]).products.order(sort_column + ' ' + sort_direction).limit(11)
else
  @products = Store.find(params[:id]).products.order(sort_column + ' ' + sort_direction).limit(12).offset(@page*12-13)
end

@products.instance_eval <<-EVAL
  def current_page
    #{@page}
  end
  def total_pages
    @@total_pages
  end
EVAL

Probably not the right way to do it, but it works for my purposes.

Chinsky
  • 55
  • 9