Guest User

Untitled

a guest
Feb 21st, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. # Easy ActiveRecord sorting with named_scopes and resources_controller
  2. # this goes in your initializers, lib directory or as a plugin
  3. module ClassMethods
  4. def sortable_with(*fields)
  5. sorts = fields.inject({}) do |h,f|
  6. h[:"#{f}_asc"] = "#{f} ASC"
  7. h[:"#{f}_desc"] = "#{f} DESC"
  8. h
  9. end
  10. write_inheritable_attribute(:sortable_fields,sorts)
  11. class_inheritable_reader :sortable_fields
  12. named_scope :sort_by, lambda { |*args|
  13. return {} if args.compact.blank?
  14. {:order => sortable_fields[args.first.to_sym]}
  15. }
  16. end
  17. end
  18.  
  19. # in your models
  20. class Post < ActiveRecord::base
  21. sortable_with :title, :created_at
  22. end
  23.  
  24. # now we can sort by :title_asc, :title_desc, :created_at_asc and :created_at_desc
  25.  
  26. # In your controller
  27.  
  28. class PostsController < ApplicationController
  29. resources_controller_for :posts
  30.  
  31. protected
  32.  
  33. # this can actually go in the app controller
  34. # it won't fail if params[:sort] is nil
  35. # you can chain other named_scopes if you want
  36. def find_resources
  37. params[:sort] ||= resource_service.sortable_fields.keys.first
  38. resource_service.sort_by(params[:sort]).paginate(:page => params[:page])
  39. end
  40. end
  41.  
  42. # add this partial to any view you want to add sort links to
  43. # app/views/shared/_sort_by.html.erb
  44. # you can prettify this with some helpers
  45.  
  46. sort by:
  47. <%= controller.resource_service.sortable_fields.collect do |key,value|
  48. link_to key, params.dup.update(:sort => key), :class => ((params[:sort].to_s==key.to_s) ? 'current' : '')
  49. end.join(' | ') %>
Add Comment
Please, Sign In to add comment