Andrea T. Andrea T. - 2 months ago 21
Ruby Question

Ajax pagination with Kaminari works, but how to update page_entries_info?

I am new to Ruby on Rails and after an intensive search to find an answer here, I decided to post my question:

I have implemented Ajax pagination with Kaminari according to the awesome git log example from Akira Matsuda here.

The pagination itself works great, but the 'page_entries_info' that shows which entries are being listed, i.e. "Displaying favorites 11 - 20 of 34 in total" does not update. It stays with the initial value "Displaying favorites 1 - 10 of 34 in total".

I have added the ":remote => true" option, without success. My code looks like this:

index.html.erb

<h1>All Favorites</h1>

<div id="paginator" class="pagination_div center">
<%= paginate @favorites, :remote => true %>
</div>

<div class="pagination_count pull-left">
<%= page_entries_info @favorites, :remote => true %>
</div>

<table class="search_results table table-hover">
<thead>
<tr>
<th>ID</th>
<th>User Id</th>
<th>User email</th>
<th>Lesson Id</th>
<th>Lesson name</th>
<th></th>
</tr>
</thead>
<tbody id="favorites">
<%= render 'favorite' %>
</tbody>
</table>


I render a partial "_favorite.html.erb":

<% @favorites.each do |favorite| %>
<tr>
<td><%= favorite.id %></td>
<td><%= favorite.user_id %></td>
<td><%= favorite.user.email %></td>
<td><%= favorite.lesson_id %></td>
<td><%= favorite.lesson.name %></td>
<td><img class="delete_favorite" src="<%=asset_path('trash.png')%>" lid="<%= favorite.lesson_id %>"></td>
</tr>
<% end %>


Here is my index.js.erb:

$('#paginator').html('<%= escape_javascript(paginate(@favorites, :remote => true).to_s) %>');
$('#favorites').html('<%= escape_javascript render('favorite') %>');


favorites_controller.rb

class FavoritesController < ApplicationController
respond_to :json

load_and_authorize_resource
before_action :verify_if_logged_in

def index
@favorites = Favorite.all.page(params[:page])
end
...
end


favorite.rb

class Favorite < ActiveRecord::Base
belongs_to :user
belongs_to :lesson
end


Thanks a lot.

Answer

I found a solution by adding the following code in index.js.erb:

 $('#counter').html('<%= escape_javascript(page_entries_info(@favorites, :remote => true).to_s) %>');

and adding id="counter" to the div in index.html.erb:

<div id="counter"class="pagination_count pull-left">
  <%= page_entries_info @favorites, :remote => true %>
</div>