Martin Rails Martin Rails - 1 year ago 95
Ruby Question

Rails Search and add filters to the search - geocoder

I would like some advices on the way to add a filter , on my search form with geocoder.

I got a User model and Animal model (animals got a Type argument)

And a join table : Animal_User with Animal_ID / User_ID)

Right now, I can locate Users around a city with the choice of Kilometers around that city.That's working fine.

I would like to add the filter on the type of animal, that would be great :)

Search would look like this : London > 10KM > Filter on Type : dogs

Many thanks in advance if you have a glimpse of an idea on how to do that. You will find the search html and the controller. If you need User Model or Animal model i can post it too ( it's really standard Has_many / has_many though association)


<div class="search-bar">
<%= form_tag search_path, :class => "webdesigntuts-workshop", method: :get do %>
<%= label :user, "" %>
<%= text_field_tag :city, params[:city], placeholder: 'City', :input_html => { :value => 'Paris' } %>

<%= label :distance, "" %>
<%= text_field_tag :distance, params[:distance], placeholder: 'km', :input_html => { :value => '10' } %>

<%= submit_tag "Search" %>
<% end %>

search controller

class SearchsController < ApplicationController
def search
if params[:city].present?
@searchs = User.near(params[:city], params[:distance] || 10).where("id != ?",
@searchs = User.all.where("id != ?",


Answer Source

Try this, I'm basing it on Active Record Querying:

User.joins(:animals).where(id:, animals: {type: params[:animal_type]}).near(params[:city], params[:distance] || 10)

This assumes that your User model has_many :animals (being able to write Rails models DSL like this is awesome)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download