Created
December 8, 2008 15:53
-
-
Save ismasan/33498 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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