Rails|Ransack|Geocoder – Sort data by distance

If your application connects local businesses to local customer, then you might have used Ransack for sorting and searching of records. For geocoding and reverse-geocoding, you might be using Geocoder gem. If you want to let users to sort results by distance then its pretty easy.

Things to remember,

  • If you use Model.near([lat, long]) method, Ransack adds a new column called distance to the ActiverecordRelation object. You can access the method distance by prying.


In view

# In index.slim | remember it's Slim format template
  = sort_link @q, :distance

In controller

# garares_controller.rb
def index

  if !params[:max_radius].present? && !params[:min_radius].present? && !params[:q][:s]
    @q = Garage.ransack(params[:q])
    @q = donut_search

  @garages = @q.result.order(params[:q][:s]).decorate


Explanation: If you might notice, you will see params as below when you pry the request after you click the Sorting link

Parameters: {"commit"=>"Search", 
  "s"=>"distance asc"
}, "utf8"=>"✓"}

luckily, since the column name is also distance so the valid data to sort a table data using a particular column is .order("column_name direction_of_order")

Note: if you change the link name from :distance to :something_else, this solution will not work and you know what to do.

Feel free to communicate with me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s