Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Meta Search or Ransack with Geocoder

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.

like image 760
user970203 Avatar asked Sep 29 '11 02:09

user970203


1 Answers

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!

like image 82
DaveStephens Avatar answered Nov 15 '22 05:11

DaveStephens