Search code examples
ruby-on-railsrubypostgresqlproximityrails-geocoder

Adding proximity filter to user search


We have a user search set up on our application, so far just based on text content queries.

So here's what I have:

in models/user.rb

def self.search(query)
  where("description ilike ?", "%#{query}%")
end

in app/controllers/users_controller.rb

class UsersController < ApplicationController
  before_action :authorized?
  def index
    @users = User.all
    if params[:search]
      @users = User.search(params[:search]).order("created_at DESC")
    else
      @users = User.all.order('created_at DESC')
    end
  end

in views/index.html.erb

<%= form_tag(users_path, :method => "get", id: "search-form") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Users" %>
  <%= submit_tag "Search", :name => nil %>
<% end %>

We're using rails and postgres. Geocoder gem is installed. We are storing current latitude and longitude in separate columns.

How would I add a proximity search filter, and what steps would I take in terms of MVC?

location is being stored in our scheme like this

 create_table "users", force: :cascade do |t|
    t.float    "latitude"
    t.float    "longitude"

Solution

  • got it. I modified my index function on users controller to

    if params[:search]
      @users = User.search(params[:search]) \
        .near([current_user.latitude, current_user.longitude], 10) \
        .order("created_at DESC")
    end