ismasan (owner)

Revisions

gist: 33498 Download_button fork
public
Public Clone URL: git://gist.github.com/33498.git
Embed All Files: show embed
named_scope_and_resources_controler.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# 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(' | ') %>