module ScopedSearch::RailsHelper
Public Instance Methods
sort(field, as: nil, default: "ASC", html_options: {}, url_options: params)
click to toggle source
Creates a link that alternates between ascending and descending.
Examples:
sort :username sort :created_at, as: "Created" sort :created_at, default: "DESC"
-
field
- the name of the named scope. This helper will prepend this value with “ascend_by_” and “descend_by_”
This helper accepts the following options:
-
:as
- the text used in the link, defaults to whatever is passed to ‘field` -
:default
- default sorting order, DESC or ASC -
:html_options
- is a hash of HTML options for the anchor tag -
:url_options
- is a hash of URL parameters, defaulting to ‘params`, to preserve the current URL parameters.
On Rails
5 or higher, parameter whitelisting prevents any parameter being used in a link by default, so ‘params.permit(..)` should be passed for `url_options` for all known and permitted URL parameters, e.g.
sort :username, url_options: params.permit(:search)
# File lib/scoped_search/rails_helper.rb 27 def sort(field, as: nil, default: "ASC", html_options: {}, url_options: params) 28 29 unless as 30 id = field.to_s.downcase == "id" 31 as = id ? field.to_s.upcase : field.to_s.humanize 32 end 33 34 ascend = "#{field} ASC" 35 descend = "#{field} DESC" 36 selected_sort = [ascend, descend].find { |o| o == params[:order] } 37 38 case params[:order] 39 when ascend 40 new_sort = descend 41 when descend 42 new_sort = ascend 43 else 44 new_sort = ["ASC", "DESC"].include?(default) ? "#{field} #{default}" : ascend 45 end 46 47 unless selected_sort.nil? 48 css_classes = html_options[:class] ? html_options[:class].split(" ") : [] 49 if selected_sort == ascend 50 as = "▲ ".html_safe + as 51 css_classes << "ascending" 52 else 53 as = "▼ ".html_safe + as 54 css_classes << "descending" 55 end 56 html_options[:class] = css_classes.join(" ") 57 end 58 59 url_options = url_options.to_h if url_options.respond_to?(:permit) # convert ActionController::Parameters if given 60 url_options = url_options.merge(:order => new_sort) 61 62 as = raw(as) if defined?(RailsXss) 63 64 content_tag(:a, as, html_options.merge(href: url_for(url_options))) 65 end