Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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 =
# copy the current search terms but exclude meta_sort
search_array =
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('&') << '&'
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;'
uri << "custom_sort=#{sort_term}.asc"
link_to(raw(sort_label), uri)
# 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 =[: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'
@companies = @search.all.uniq.sort_by{ |a| a.antibodies.length }.paginate :page => params[:page], :per_page => 20
@custom_sort = 'n_antibodies.asc'
@search.meta_sort ||= 'name.asc'
@companies = @search.all.paginate :page => params[:page], :per_page => 20
# 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