Skip to content

Instantly share code, notes, and snippets.

@damien
Created September 29, 2014 03:03
Show Gist options
  • Save damien/0dfb8c2824178f12c4a5 to your computer and use it in GitHub Desktop.
Save damien/0dfb8c2824178f12c4a5 to your computer and use it in GitHub Desktop.
class SearchController < ApplicationController
def index
if search_params.blank? && where_params.blank?
@portfolios = Portfolio
.includes([:user, :portrait])
.where(published: true)
.order('created_at DESC')
else
@portfolios = search_portfolio search_params, where_params
end
end
private
# Construct a search query using search arguments
def search_portfolio(search: nil, coordinates: nil)
search_args = [ { include: [:user, :portrait] } ]
# Find portfolios near a given location if coordinates
# have been provided
if coordinates
search_args.unshift({
where: {
location: {
near: Geocoder.coordinates(coordinates),
within: '300mi'
}
}
})
end
# Filter results with a search query if a search
# term was provided
search_args.unshift(search) if search
Portfolio.search(*search_args)
end
# Return `params[:search]` if it is present and non-empty,
# otherwise return nil
def search_params
params.fetch(:search, nil).present? ? params[:search] : nil
end
# Return `params[:where]` if it is present and non-empty,
# otherwise return nil
def where_params
params.fetch(:where, nil).present? ? params[:where] : nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment