invaino invaino - 10 months ago 53
Ajax Question

Rails3 - Sort and Paginate with Kaminari + AJAX + unobtrusive javascript

I have successfully set up an ajax pagination with Kaminari.

In order to add a sort feature I followed this great Railscast and replaced will_paginate by Kaminari.

The pagination works great but the sort works just the first time because the sort_column and the sort _direction are not updated.

I can't figure out why.

Here is my code :

Controller :

def index
@questions = Question.order(sort_column + " " + sort_direction).page(params[:page])



def sort_column
Question.column_names.include?(params[:sort]) ? params[:sort] : "created_at"

def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : "desc"

I have added
:remote => true, :method => :get

ApplicationHelper :

def sortable(title = nil, column)
title ||= column.titleize
direction = column == sort_column && sort_direction == "asc" ? "desc" : "asc"
link_to title, params.merge(:sort => column, :direction => direction), :remote => true, :method => :get

index.html.erb :

<%= sortable "created_at" %><br/>
<div id="questions"><%= render @questions %></div>
<div id="paginator"><%= paginate @questions, :remote => true %>

index.js.erb :

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

Is this a problem with the
:remote => true, :method => :get
part ? If I remove it the sort works but without ajax.

Answer Source

I would like you suggest to take a look at this screencast.

It does the sort data columns very easy to implement.