Reputation: 1173
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?
Upvotes: 1
Views: 3506
Reputation: 1567
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
Upvotes: 2
Reputation: 1062
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.
Upvotes: 2
Reputation: 882
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.
Upvotes: -2
Reputation: 76774
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
Upvotes: -1