开发者

Best practice for sorting data in a Rails app

In an 'index' method I'm always listing Objects. What is the best practice of handling sorting for this? So in the view I'd want a dropdown that lets me select b开发者_如何学Pythony [Created At, Size, Price, ...]. An example would be much much appreciated.


I see this this as more of a usability best-practices question.

The answer really depends on how the information is displayed. Also on how much of it is there.

If all of the information the user can sort with is displayed on the page in table format, then I would use link_to_remote to update only the table with new sorting.

If your list is long enough to want to sort by different criteria, you'll probably be doing some kind of pagination. So this example uses will paginate.

Controller

def index
  order = params[:order] 
  find_options = {:per_page => params[:per_page] || 20,
     :page => params[:per_page] || 1),
     :order => order
  }

  @things = Things.paginate(find_options)
  respond_to do |format|
    format.html # default action
    # update only the table partial if action is a java script request.
    format.js render :update do |page|
      page.replace_html :things_table_body, :partial => things, :collection => @things
    end
  end
end

It doesn't make sense to do this without partials.

View:

...
<table>
 <tr div="table_header">
   <th>
     <%= link_to_remote "Name",  things_url(:order => :name), :href => things_url(:order => :name)%>
   </th>
   <th>
     <%= link_to_remote "Created At",  things_url(:order => :name), :href => things_url(:order => :name)%>
   </th>
 </tr>
<tbody div="things_table_body">
<%= render :partial => :thing, :collection => @things} %>
</table>
<%= will_paginate @things %>
...

The href option to the link_to_remote allows fallback to html requests in the event that your user doesn't have javascript enabled.

things partial:

<tr>
  <td>
    <%=thing.name%>
  </td>
  <td>
    <%=thing.created_at%>
  </td>
</tr>

It's left as an exercise for the reader to work out how to toggle between ascending and descending sorting.

In the event you're not listing all sortable attributes. A select box is fine. Personally I'd go for Radio buttons if the list of ways to sort isn't too long. Either way the controller code will looking almost identical to what I posted before.


Suppose I have a Book model and I want to fetch a number of books sorted on some particular field. To do this quickly I would create a method, say fetch_books which will take an options hash. This hash will hold the parameter on which the user wants to sort the list of the books returned.

In your model you can have,

class Book < ActiveRecord::Base
  def self.fetch_books(options)
    find(:all, :order => options[:sort_by])
  end
end

In your controller,

class BooksController < ApplicationController
  @books = Book.fetch_books(params)
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜