Skip to content

Instantly share code, notes, and snippets.

@jzellman
Created November 10, 2009 17:55
Show Gist options
  • Save jzellman/231098 to your computer and use it in GitHub Desktop.
Save jzellman/231098 to your computer and use it in GitHub Desktop.
<h1>Listing people</h1>
<table>
<tr>
<th><%= sorted_people_url("First name", "first_name") -%></th>
<th><%= sorted_people_url("Last name", "last_name") -%></th>
<th><%= sorted_people_url("Personal Email", "email") -%></th>
<th><%= sorted_people_url("Age", "age") -%></th>
</tr>
<% @people.each do |person| %>
<tr>
<td><%=h person.first_name %></td>
<td><%=h person.last_name %></td>
<td><%=h person.email %></td>
<td><%=h person.age %></td>
<td><%= link_to 'Show', person %></td>
<td><%= link_to 'Edit', edit_person_path(person) %></td>
<td><%= link_to 'Destroy', person, :confirm => 'Are you sure?', :method => :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New person', new_person_path %>
class PeopleController < ApplicationController
# GET /people
# GET /people.xml
def index
column, order = parse_order(params[:order])
@people = Person.order_by(column, order)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @people }
end
end
#... more actions here
protected
def parse_order(column_order_str)
# if no column_order param, then return a default ordering
# right now im just default ordering it by id desc, you can change
# this to whatever
return :id, :desc if column_order_str.nil?
split = column_order_str.split("_")
column = split[0..-2].join("_")
order = split[-1]
return column, order
end
end
module PeopleHelper
# column name is the name of html header column ("First Name", "Last Name", "Last Modified"
# field is the field on the person model (database column: first_name, last_name, updated_at)
# returns a link to #index with an order param specifying the order, if params[:order] exist and
# matches the column, the order is the opposite.
# ie params[:order] = "age_asc" then
# sorted_people_url("age", :age) # <a href="http://localhost:3000/people?order=age_desc">Age</a>
#
def sorted_people_url(column_name, field)
existing_field_order = params[:order].nil? ? nil : params[:order].downcase
order = if existing_field_order &&
existing_field_order.starts_with?(field.downcase) &&
existing_field_order.ends_with?("desc")
:asc
else
:desc
end
link_to(column_name, people_url(:order => "#{field}_#{order}"))
end
end
class Person < ActiveRecord::Base
# column is the column to sort by
# order is ASC or desc
#
named_scope(:order_by, lambda{|column, order| {:order => "#{table_name}.#{column} #{order}" }})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment