脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

tablesoterをRailsで使う方法 + FilterとSort機能の使い方

jueryプラグインのtablesorterをRailsで使う方法です。

f:id:portaltan:20150916151141p:plain

tablesorterはtableをsortしたりfilteringするjQueryプラグインです。

ソースコード

まずはじめに、tablesorterには本家とforkして他の人が開発しているPageの二つのドキュメントがあります
本家:
http://tablesorter.com/docs/

Fork:
https://mottie.github.io/tablesorter/docs/

今回はForkの方を利用する方法を記載します。

ライブラリのダウンロード

app/assets/javascriptsディレクトリに

をダウンロードして配置します
https://mottie.github.io/tablesorter/docs/#Download


tablesorterの処理を記述

tableの作成

まずは普通にhtmlでtableを作成します。

<table class="tablesorter" border="1">
  <thead>
    <tr>
      <th>column1</th>
      <th>column2</th>
      <th>column3</th>
    </tr>
  </thead>
  <tbody class="table-contents">
    <tr>
      <td>1</td>
      <td>3</td>
      <td>2</td>
    </tr>
    <tr>
      <td>foo</td>
      <td>baz</td>
      <td>bar</td>
    </tr>
  </tbody>
</table>
  • class属性にtablesorterを指定します

この時点ではこんな感じのtableです。
f:id:portaltan:20150916142953p:plain

jsの設定(tablesorter_test.js)
$('table.tablesorter').tablesorter({ 
});
  • 名前はなんでもいいです

application.jsの編集

app/assets/javascripts/application.jsに以下を記述します

//= require jquery-2.1.1.min
//= require jquery.tablesorter.combined.js
//= require tablesorter_test.js
  • 順番は逆にしないようにしましょう
  • javascriptsディレクトリ以下全てを読み込む設定にしている場合はそのままでOKです

これだけで一番単純なsort機能は利用できるようになりました
f:id:portaltan:20150916143135p:plain

  • 各項目でsortすることが出来ます

TableSorterの他の機能の利用

まずデフォルトのTableがこのような状態です
f:id:portaltan:20150916143451p:plain

デフォルトでsortさせる

上のままではPage読み込み時にはsortは行われていません。
これを最初から特定のcolumnでsortしておくことが可能です。

sortList: [[${何列目でsortするか}, ${昇順(0)か降順(1)か}]]
  • 一番左の列を0とします

例1

$('table.tablesorter').tablesorter({
    sortList: [[0,0]],
});

f:id:portaltan:20150916143818p:plain

  • column1(0)で昇順(0)でsortされています

例2

$('table.tablesorter').tablesorter({
    sortList: [[2,1]],
});

f:id:portaltan:20150916144212p:plain

  • column3(2)で降順(1)でsortされています

Filter機能

上でjquery.tablesorter.combined.jsを使用している場合は、defaultでfilter機能も利用できます

widgets: ["filter"]

例1

$('table.tablesorter').tablesorter({
    widgets: ["filter"],
})

f:id:portaltan:20150916145202p:plain

  • ちょっとずれていますが、filterボックスが各columnに表示され、入力された値でfilteringされうようになりました

filter機能を限定することも可能です

widgets: ["filter"],
headers: {${何個目の列か}: { filter: false }},

例2

$('table.tablesorter').tablesorter({
    widgets: ["filter"],
    headers: {0: { filter: false }, 2: { filter: false }},
});

column1(0)とcolumn3(2)のfilter機能は廃止(false)されています
f:id:portaltan:20150916145913p:plain

リセットボタン

filterに入力した値をリセットするボタンも簡単に作れます

まずはボタンを作ります

<button class="reset-filter-button">Reset Filter</button>

このボタンにリセット機能をセットします

widgetOptions : {
    filter_reset : 'button.reset-filter-button',
}

例1

$('table.tablesorter').tablesorter({
    widgets: ["filter"],
    widgetOptions : {
        filter_reset : 'button.reset-filter-button',
    }
});

これで入力値をリセットすることができます。
f:id:portaltan:20150916150609p:plain

f:id:portaltan:20150916150515p:plain