Search code examples
ruby-on-railsransack

Rails ransack filter on multiple instances


I have a poll app that allows to create polls as draft or published. Admin can see all. Users only published ones. Then I am using ransack to filter.

This is my controller:

    @q = Poll.includes(:division).includes(:vote_options).ransack(params[:q])
    @p = Poll.where(published: '1').includes(:division).includes(:vote_options).ransack(params[:p])
    @polls = @q.result.order(:sort)
    @published_polls = @p.result.order(:sort)
    @display_polls = current_user.admin_role? ? @polls : @published_polls

As I needed to create two instances of Poll I added @p beside @q. And I'm not sure this is the right approach.

In my view I have

<% @display_polls.each_with_sortable_id do |poll, sortable_id| %>

For ransack filters I have:

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

Published and unpublished items show correctly as expected. But ransack filters won't work.

How can I make filters work again?


Solution

  • I think it might be because your search_form_for is only searching on @q. I think this might be a better approach in your controller:

    if current_user.admin_role?
        @q = Poll.includes(:division, :vote_options).ransack(params[:q])
    else
        @q = Poll.where(published: '1').includes(:division, :vote_options).ransack(params[:q])
    end
    
    @polls = @q.result.order(:sort)