As mentioned by @Slava.K, you can adjust the Ransack configuration in an initializer or override Ransack's FormHelper.
But if you want to do this manually in your view, you can! Use the sort_url
helper to create the link, then check Ransack's sorts
array to determine which sort is being used and what direction (asc/desc), then render the appropriate icon.
This example will display one of three icons (up/down/neutral) depending on the field if it was sorted or not, and which direction it was sorted. We will use the fontawesome-sass gem to render an icon but you can replace the icon()
helper with whatever icon method/markup you want to use.
# some_view.html.slim
= link_to sort_url(@q, :name)
# Display label
span Name
# Sort icon
# Check if ransack applied a sort to this field
- sort = @q.sorts.find {|s| s.name == 'name'}
# Render appropriate icon (up/down/neutral)
# If this column is sorted by 'asc' display 'sort-up' icon
= icon(:fas, 'sort-up') if sort.present? and sort.dir == 'asc'
# If this column is sorted by 'desc' display 'sort-down' icon
= icon(:fas, 'sort-down') if sort.present? and sort.dir == 'desc'
# If no sort is applied display a neutral icon
= icon(:fas, 'sort') unless sort.present?
We can simplify the code above by using a ternary operator, like so...
# some_view.html.slim
= link_to sort_url(@q, :name)
span Name
- sort = @q.sorts.find {|s| s.name == 'name'}
= icon :fas, sort.present? ? (sort.dir == 'asc' ? 'sort-up' : 'sort-down') : 'sort'
If you want to get really fancy and keep your view's DRY, you could create a helper method similar to Ransacks sort_url
or sort_link
and place this markup into it. It could look something like this...
# some_helper.rb
def custom_sort_link(search_object, attribute, *args)
link_to sort_url(search_object, attribute, *args) do
sort = search_object.sorts.find {|s| s.name == attribute.to_s}
content_tag(:span, attribute.to_s.capitalize) + icon(:fas, sort.present? ? (sort.dir == 'asc' ? 'sort-up' : 'sort-down') : 'sort')
end
end
And then in your view, call custom_sort_link
like so...
# some_view.html.slim
= custom_sort_link(@q, :name)
As a side note, if you have FontAwesome Pro, the duotone icons look way better. Just replace :fas
with :fad
.