LoginSignup
23
26

More than 5 years have passed since last update.

ransackのsort_linkをajaxで使う(サンプルアプリ付き)

Posted at

ransackのsort_link

ransackという検索機能を実現するgemがありますが、このgemはsort_linkというソート用のhelperも用意しています。
これがとても簡単で便利で、kaminariと合わせたりしてあっという間にかっこいい一覧の出来上がりです。
でも、僕の探し方が悪いのか、sort_linkドキュメントが全然みあたらなかったのです。特にajaxで使おうとすると、全然情報がなくて困ってしまいました。

仕方ないのでソースを確認しました。

まず、ransackのsort_linkは以下のように使います。
表示名以降は省略可能です。

sort_link(@search, :カラム名, 表示名, urlオプション, htmlオプション)

これを踏まえて、ajaxでソートしてみましょう。

ajaxでソートする

必要最小限で抜き出すと、以下のようになります。

index.html.haml
#users_index
  = render partial: 'users_table', locals: { users: @users }
_users_table.html.haml
- url_options = { action: :index }
- html_options = { remote: true, method: :get }

%table
  %thead
    %tr
      %th= sort_link(@search, :name, url_options, html_options)
index.js.haml
:plain
  $('#users_index').html("#{escape_javascript(render partial: 'users_table', locals: { users: @users })}")
users_controller.rb
def index
  @search = User.search(params[:q])
  @users = @search.result
end

サンプルアプリ

というわけで、サンプルアプリを作ってみました。kaminariと合わせてページネーション+ソートのできる一覧画面です。

23
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
26