Search code examples
searchruby-on-rails-4filterransack

Rails4 Multiple Ransack search on same controller


I have Ransack set on my Events model

In my controller I have three actions that refer respectively to index, upcoming and myevents. index displays all events upcoming displays events that will come myevents displays user own events

Since they all look the same in view, upcoming and myevents use the index template

class EventsController < ApplicationController

def index
  @q = Events.search(params[:q])
  @events = @q.result.includes(:address, user:[:address]).page(params[:page])
end

def upcoming
    @q = Card.future.search(params[:q])
    @cards = @q.result.includes(:address, user:[:address]).page(params[:page])
    render template: 'events/index'
end

def myevents
  @q = current_user.events.search(params[:q])
  @events = @q.result.includes(:address, user:[:address]).page(params[:page])
  render template: 'events/index'
end

end

Notice the future scope scope :future, -> { where('rdv >= ?', Date.today) } end

Everything works fine except that after clicking the "search button" on upcoming events or my events, the search renders the events#index action, thus the "future" scope is ignored, as the current_user is.

I know that I can define the ransack search in routes, and add the cards#search action, but

PROBLEM : how can I make my events#upcoming persistant after clicking the search button ? Same for events#upcoming and events#myevents

Maybe my logic is wrong. Thank you very much for your help

Note that I do not use post because I have will_paginate working with ajax, and I only able to make it properly works with get method.


Solution

  • Change each search_form_for to specify the path to the page you want to load the results, e.g.:

    <%= search_form_for @q, url: your_path do |f| %>