admitme_sam
admitme_sam

Reputation: 169

find events within date range of search results in rails/ruby

I'm struggling a bit to get this to work, I have a working search function on my website using searchkick.

However i'm wanting to allow my users to filter the results on the results page.

This is my controller for reference:

def search
    @events = Event.page(params[:page]).per(10).search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)
    if @events.results.any?
      render 'events/results'
    else
      @popevents = Event.limit(3).order('RANDOM()')
      render 'events/noresults'
    end
  end

Now what i'm wanting is a simple date picker in the view, that allows the users to search a date range (to and from) of the events returned then on submit it would return only the events in that range. I've looked at filterrific but got confused and wasnt sure thats what i actually need?

Any help would be much appreciated!

edit

So if i have this:

<label for="datefrom">Date From:</label>
      <input type="date" id="datefrom" class="form-control" name="datefrom" value="dd/mm/yyyy">
      <label for="dateto">Date To:</label>
      <input type="date" id="dateto" class="form-control" name="dateto" value="dd/mm/yyyy">

<div style="float:right">
        <button class="btn btn-info" name="button">Apply Filters</button>
      </div>

I'm wondering what i need to put on the button, And also would the bit in the controller go into the if @events.results.any? section?

Thanks

Upvotes: 0

Views: 629

Answers (1)

Bartłomiej Gładys
Bartłomiej Gładys

Reputation: 4615

You can do something like this:

In the view put your date_pickers with input like this:

<%= form_tag your_search_path, method: :post do%>
  # here your datepicker content

  <%= submit_tag 'Send' %>
<% end %>

in your controller:

def search
    @events = Event.page(params[:page]).per(10).search(params[:search], misspellings: { distance: 1 }, order: { date: :asc, eventname: :asc }, match: :word_start, page: params[:page], per_page: 20)
    @events = @events.where(created_at: (Time.parse(params[:datefrom])..Time.parse(params[:dateto]))
    if @events.results.any?
      render 'events/results'
    else
      @popevents = Event.limit(3).order('RANDOM()')
      render 'events/noresults'
    end
 end

Upvotes: 1

Related Questions