Skip to content

Instantly share code, notes, and snippets.

@ismasan
Created December 8, 2008 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ismasan/33498 to your computer and use it in GitHub Desktop.
Save ismasan/33498 to your computer and use it in GitHub Desktop.
# Easy ActiveRecord sorting with named_scopes and resources_controller
# this goes in your initializers, lib directory or as a plugin
module ClassMethods
def sortable_with(*fields)
sorts = fields.inject({}) do |h,f|
h[:"#{f}_asc"] = "#{f} ASC"
h[:"#{f}_desc"] = "#{f} DESC"
h
end
write_inheritable_attribute(:sortable_fields,sorts)
class_inheritable_reader :sortable_fields
named_scope :sort_by, lambda { |*args|
return {} if args.compact.blank?
{:order => sortable_fields[args.first.to_sym]}
}
end
end
# in your models
class Post < ActiveRecord::base
sortable_with :title, :created_at
end
# now we can sort by :title_asc, :title_desc, :created_at_asc and :created_at_desc
# In your controller
class PostsController < ApplicationController
resources_controller_for :posts
protected
# this can actually go in the app controller
# it won't fail if params[:sort] is nil
# you can chain other named_scopes if you want
def find_resources
params[:sort] ||= resource_service.sortable_fields.keys.first
resource_service.sort_by(params[:sort]).paginate(:page => params[:page])
end
end
# add this partial to any view you want to add sort links to
# app/views/shared/_sort_by.html.erb
# you can prettify this with some helpers
sort by:
<%= controller.resource_service.sortable_fields.collect do |key,value|
link_to key, params.dup.update(:sort => key), :class => ((params[:sort].to_s==key.to_s) ? 'current' : '')
end.join(' | ') %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment