Question

After struggling for a while with filtering and sorting index views in Rails I've ended up using the Ransack gem to assist. Mostly it's very awesome but there seems to be a slight disconnect between what Ransack does (at least by default) and what I'm trying to do at the moment.

What I actually want to do is just apply a filter to a form to display data on the index, but along with other summary data relating to the index view (e.g. totals etc.). However, as I understand a search or filter action through Ransack actually filters all entries and then the index view responds only to those filtered items, i.e. the index will only return on the newly filtered data. Therefore, I can't seem to return values on the full, unfiltered, set in the same view as the filtered data. A simplified example is below, for Guests responding to attend a function ('rsvp' as a boolean):

Controller:

def index
  @search = Guest.search(params[:q])
  @guests = @search.result
end

View:

<td><%= @guests.where(rsvp: true).count %></td>

  <%= search_form_for @search do |f| %>
  <div class="dropdownlist span2">
    <%= f.select :rsvp_eq, options_for_select([['All Guests', ''],['Confirmed attending', true], ['Not attending', false]], :selected => :wedding) %>
    <%= f.submit "Filter" %>
  </div>
  <% end %>
</div>
<table class="table">
  <tr>
    <th>Guest</th>
  </tr>
  <% @guests.each do |b| %> 
  <tr>
    <td><%= b.name %></td>
  </tr>
  <% end %>
</table>

In this example the filter works effectively, but the count of all guests where rsvp=true only counts from the filtered data. I.e. if I filter by rsvp=false, the total count for rsvp=true would be zero, regardless of the actual number of true responses in the database. Is there a simple way around this, i.e. returning '@guests = Guests.all' in the index, and still returning the limited search results as well but just for the form? Am I missing something simple?

Was it helpful?

Solution

You're right, @guests will return the filtered guests only, so if you want to have the rsvp count of all guests, your only option is to add another instance variable in the controller index method:

@guests_count = Guest.where(rsvp: true).count

Of course this means an extra query to the database and you have to decide if this count information is important enough to grant an extra DB call.

On the other hand: in the context of filtered guests, it might be confusing for a visitor to see another guest rsvp count than the actual displayed quests.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top