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.

Solution

In view

# In index.slim | remember it's Slim format template
button.btn.btn-default[type="button"]
  = sort_link @q, :distance

In controller

# garares_controller.rb
def index
  modify_search_query

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

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

  restore_search_query
end

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", 
"q"=>{
  "name_or_address_or_city_or_state_or_zip_or_about_cont_any"=>"",
  "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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s