Question

I'm following this railscast: http://railscasts.com/episodes/340-datatables.

I'm trying to get my datatables to paginate at every 10 items. My code looks like this:

def index
  @search = Product.search do |query|
    query.fulltext params[:sSearch]
    query.with(:store_id, @store.id)
    query.paginate(:page => page, :per_page => per_page)
  end
  @products = @search.results

  @headers = @products.map(&:data).flat_map(&:keys).uniq

  @product_data = @products.map{ |product| product[ :data ].values }

  respond_to do |format|
    format.html
    format.json do
      render :json=> {
        "sEcho"               => params[:sEcho].to_i,
        "iTotalRecords"       => @products.count,
        "iTotalDisplayRecords"=> @products.count,
        "aaData"              => @product_data.as_json
      }
    end
  end
end

private
  def page
    params[:iDisplayStart].to_i/per_page + 1
  end

  def per_page
    params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
  end

I have the will_paginate gem installed, but the datatable doesn't seem to recognize that it should be paginating, it shows up to 10 records and has the pagination buttons disabled.

What's going wrong?

No correct solution

OTHER TIPS

I'm no rails developer, but it seems to me that the problem is:

"iTotalRecords"       => @products.count,

@products.count it's the record count when the query is already paginated (always 10 or less depending on the page).

Try setting this value to the total number of records of the query whitout any pagination.

I think the issue is you should be using total_entries instead of count.

So change this:

"iTotalDisplayRecords"=> @products.count

to this:

"iTotalDisplayRecords"=> @products.total_entries

Buttons

You'll need to include <%= will_paginate @products %> in your view (this allows you to refresh the datatable with new paginated content each time:

#app/views/products/datatable.html.erb
<<datatable>>
<%= will_paginate @posts %>

Records

If you're seeing 10 results is because of will_paginate, it means you're on the right track. The gem works by using limit and offset to create a "scope" of the SQL query

Essentially, if you've implemented the gem correctly, it will only pull back the required data from the database for your view, hence the 10 results

you are doing it the wrong way. First donot use will_paginate when you are using datatables on the same page. You are seeing no pagination because, will paginate is limiting the no of records to 10. So for datatables to recognize and paginate your table you have to print all records on the page and datatables will find that there more than 10 rows in the table and paginates the table accordingly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top