Search code examples
ruby-on-railssearchfilterransackrails-geocoder

Ruby on rails. Filtering results with ransack and geocoder


I am currently working on filtering the results on my index page. I have 'gigs' that are geocoded with geocoder. I am also trying to use ransack to filter other attributes in the same model, on the same page.

So far I can filter the results with ransack fine, and separately I can filter the results by location but I cannot link the two together, for example, if I filter all gigs after a certain date, these will show, but if I the add a location into the filter query the list won't change. The map WILL show the location though.

Here's my code so far.

Gigs controller

def index
    if params[:search].present?
    @gigs = Gig.near(params[:search], 200, :order => 'distance' )
    @hash = Gmaps4rails.build_markers(@gigs) do |gig, marker|
      marker.lat gig.latitude
      marker.lng gig.longitude
      marker.title gig.title
    end
    else
    @gigs = Gig.all
    @hash = Gmaps4rails.build_markers(@gigs) do |gig, marker|
      marker.lat gig.latitude
      marker.lng gig.longitude
      marker.title gig.title
    end
  end
  @q = Gig.ransack(params[:q])
  @gigs = @q.result(distinct: true)
end

I have changed the order of things which changes the search behaviour a bit, but I cant link the two things together. I have currently left it like this just to show the code.

Index.html

<div class="search-filters">
<div class="search-location">
  <%= search_form_for @q do |f| %>
<%= form_tag gigs_path, :method => :get do %>
<p>
  <%= f.search_field :date_gteq, placeholder: "From" %>
  <%= f.search_field :date_lteq, placeholder: "Until" %>
  <%= text_field_tag :search, params[:search] %>
  <%= submit_tag "Near", :name => nil %>
</p>
<% end %>
<%= sort_link(@q, :date) %>

<% end %>

</div>
</div>

Thanks in advance for any advice in linking these together.


Solution

  • Ok after further research I realised that I could just link the two together. I left my index alone but changed the controller.

    Controller:

    def index
        if params[:search].present?
        @q = Gig.near(params[:search], 200, :order => 'distance' ).ransack(params[:q])
        @gigs = @q.result(distinct: true)
        @hash = Gmaps4rails.build_markers(@gigs) do |gig, marker|
          marker.lat gig.latitude
          marker.lng gig.longitude
          marker.title gig.title
        end
        else
        @q = Gig.ransack(params[:q])
        @gigs = @q.result(distinct: true)
        @hash = Gmaps4rails.build_markers(@gigs) do |gig, marker|
          marker.lat gig.latitude
          marker.lng gig.longitude
          marker.title gig.title
        end
      end
    end
    

    I will now clean everything up a bit.