Using Meta Search or Ransack with Geocoder
Asked Answered
U

1

6

I've created a form that supplies search criteria:

    = search_form_for @q do |f|
  %h3
    Search:
  = f.label :category_id
  %br
  = f.collection_select :category_id_eq, Category.all, :id, :name, :include_blank => true
  %br
  = f.label "Sub-Category"
  %br
  = f.collection_select :subcategory_id_eq, Subcategory.all, :id, :name, :include_blank => true, :prompt => "select category!"
  %br
  = f.label "Contains"
  %br
  = f.text_field :title_or_details_cont
  %br
  = f.submit

I want to be able to also do a search based on the "Near" functionality of the Rails Geocoder gem. Does anyone know how to incorporate an existing scope, or specifically how to use the "Near" scope with Meta Search or Ransack?

Thus far, all of my attempts have been futile.

Unlicensed answered 29/9, 2011 at 2:43 Comment(0)
L
9

This is actually quite easy to achieve simply by adding a non-search_form_for field within your form.

In my view (note the difference in the two form fields):

<%= search_form_for @search do |f| %>
    <%= f.label :will_teach, "Will Teach" %>
    <%= f.check_box :will_teach %>

    <%= label_tag :within %>
    <%= text_field_tag :within, params[:within], {:class => "span1"} %> miles
<% end %>

This then produces a param string like the following:

Parameters: {"utf8"=>"✓", "q"=>{"will_teach"=>"1"}, "within"=>"10", "commit"=>"Search"}

You can then put some conditional logic into your controller to hoover these params up, and combine Geocoder with Ransack. I check to see if the "within" parameter is present, if so, check it's a number (to_i returns 0 for anything but a number, hence the > 0 check).

I then combine the Geocoder "near" with Ransack's "search".

If the "within" parameter isn't there (i.e. the user didn't enter a number) then I search without the Geocoder bits.

Finally I'm using Kaminari, so that goes on the end of the search results:

   if params[:within].present? && (params[:within].to_i > 0)
        @search = Tutor.near(request.location.city,params[:within]).search(params[:q])
    else
      @search = Tutor.search(params[:q])
    end

    @tutors = @search.result.page(params[:page]).per(9)

Hope this helps!

Lyublin answered 27/12, 2012 at 19:16 Comment(2)
Thank you. This should probably be accepted as the answer. Either way, it really helped me out. Ta.Biodegradable
@luisenrike it's only been five years :DLyublin

© 2022 - 2024 — McMap. All rights reserved.