will_paginateでAjax
will_paginateをAjaxページに追加したので、作業内容をまとめます。
環境
- Rails 2.3.8
- will_paginate 2.3.15
参考にしたページ
概要
will_paginateのページ遷移はAjaxに対応していないので、そのままではエラーが発生してしまいます。
そこで、jQueryを使用して、will_paginateが生成するa要素クリック時のイベントを、Ajaxに変換させる事で対応しました。
ほぼ参考ページのままなのですが、なかなか動かず苦労しました。
prototype.jsの場合はこちらで行けるんじゃないでしょうか?
Controller
class ModenaviController < ApplicationController def search @model_id = params[:model_id] @center_id = params[:center_id] @machine_log_list = DailyMachineData.average_list(@model_id, @center_id, @current_time, @filter, params[:page]) render :update do |page| page.replace_html "log-list-chart", :partial => "log_list_chart" page.replace_html "log-list", :partial => "log_list" page << "ajaxifyPagination();" end end end
View
<%= will_paginate @machine_log_list, :params => { :model_id => @model_id, :center_id => @center_id }, :class => 'pagination' %>
public/javascripts/application.js
$(function(){ ajaxifyPagination(); }); function ajaxifyPagination() { $(".pagination a").click(function() { $.ajax({ type: "POST", url: $(this).attr("href"), dataType: "script" }); return false; }); }
ポイント
- controllerのrenderの最後で実行する「page << "ajaxifyPagination();"」が大切
- $.ajaxのtypeは"POST"
- will_paginateの引数"params"で、controllerにパラメータを渡せる