Skip to content

Instantly share code, notes, and snippets.

@craic
Created June 10, 2011 17:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craic/1019358 to your computer and use it in GitHub Desktop.
Save craic/1019358 to your computer and use it in GitHub Desktop.
This gist includes a Rails helper and controller code that lets you sort on custom columns alongside the meta-search gem search and sort features
# Helper method - place in application_helper.rb
def custom_sort_helper(path, sort_term, sort_label, search, sort_string)
uri = String.new(path)
# copy the current search terms but exclude meta_sort
search_array = Array.new
search.search_attributes.each { |key, val| (search_array << "search[#{key}]=#{val}") unless key == 'meta_sort' }
uri << '?'
if search_array.length > 0
uri << search_array.join('&') << '&'
end
if sort_string =~ /#{sort_term}\.desc$/
uri << "custom_sort=#{sort_term}.asc"
sort_label << '&nbsp;&#9660;'
elsif sort_string =~ /#{sort_term}\.asc$/
uri << "custom_sort=#{sort_term}.desc"
sort_label << '&nbsp;&#9650;'
else
uri << "custom_sort=#{sort_term}.asc"
end
link_to(raw(sort_label), uri)
end
# Example code for your controller index action
# In this example for a Companies controller, a company can have many Antibodies via a has_many_through association
# The code allows sorting on Company columns and on the Number of Antibodies associated with a company
def index
@search = Company.search(params[:search])
@custom_sort = nil
if params[:custom_sort] and params[:custom_sort] =~ /^n_antibodies/
if params[:custom_sort] =~ /desc$/
@companies = @search.all.uniq.sort_by{ |a| -a.antibodies.length }.paginate :page => params[:page], :per_page => 20
@custom_sort = 'n_antibodies.desc'
else
@companies = @search.all.uniq.sort_by{ |a| a.antibodies.length }.paginate :page => params[:page], :per_page => 20
@custom_sort = 'n_antibodies.asc'
end
else
@search.meta_sort ||= 'name.asc'
@companies = @search.all.paginate :page => params[:page], :per_page => 20
end
end
# Here is the code that goes into the Index view for the column that contains the Number of Antibodies
<%= custom_sort_helper(companies_path, 'n_antibodies', '# Antibodies', @search, @custom_sort) %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment