Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a controller & action for Ajax pagination with Kaminari?

I'm using the Kaminari gem for my ruby on rails application (For anybody still using will_paginate, I would recommend to consider switching! Much cleaner and more versatile).

The problem I have is that I want to specify a controller action when doing AJAX pagination, ie. get my pagination to work remotely, as such:

 <%= paginate @feeds, :param_name => :page, :remote => true%>

By default, when I set :remote => true, and add the following lines to my "pages" controller home.js.erb file, it works on my homepage. I don't even need to specify which js partial to refer to; it chooses automatically.

  $('.synopsis').html('<%= escape_javascript render('exchanges/synopsis', :feeds => @feeds)%>');
  $('.paginator').html('<%= escape_javascript(paginate(@feeds, :param_name => :page, :remote => true).to_s)%>')

BUT the catch is that this "synopsis" div is a partial that I render on a lot of different pages in my application. So on pages where the controller isn't my "pages" controller, the remote pagination no longer works.

One solution would be to add these two lines to js.erb files in my many different controllers. But that would be redundant and inelegant.

I would prefer to be able to specify in the "paginate" call, which controller and which action to use for the remote call. Then I think I would write an action like:

 def paginate_remotely
     respond_to paginate_remotely.js
 end

How would I be able to do this? It seems like such a simple question but I haven't been able to figure it out. The following certainly does not work:

 <%= paginate @feed_exchanges, :param_name => :exchange_page, :remote => true, :controller => :exchanges, :action => :paginate_remotely %>
like image 325
geb2011 Avatar asked Jan 23 '26 07:01

geb2011


1 Answers

For those who are interested, the answer is you have to specify the controller and action under a :params specification, as follows:

 <%= paginate @feed_exchanges, :params => {:controller => :exchanges, :action => :paginate_remotely}, :param_name => :exchange_page, :remote => true %>

Don't forget to write define the route for this action in config/routes.rb, and create a js partial, in my case called paginate_remotely.js.erb, containing:

 $('.synopsis').html('<%= escape_javascript render('exchanges/synopsis', :feeds => @feeds)%>');
 $('.paginator').html('<%= escape_javascript(paginate(@feeds, :param_name => :page, :remote => true).to_s)%>')
like image 154
geb2011 Avatar answered Jan 25 '26 20:01

geb2011



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!