Ransack - How to Preserve Drop Down Menus After A Ransack Search
I happen to be running a search on ransack. I am utilising drop down menus in the search. In my particular case, we want to be searching for line items (a particular type of model, which have different types of states). I am using the AASM state machine gem to acheive this particular goal.
The question is how to retain the search conditions, after you’ve submitted them. This is done using the f.collection_select
helper method.
<%= search_form_for @q, url: search_line_items_path, html: { method: :get } do |f| %>
<table class="table thead-dark table-striped table-bordered table-hover table-responsive" summary="Search Fields" >
<tr >
<th >
<h3 align="center" valign="middle">Search Fields</h3>
</th>
</tr>
<tbody>
<tr>
<td>
<%= f.label :quote_aasm_state_eq, 'Quote State is:' %>
<%= f.collection_select :quote_aasm_state_eq, Quote.aasm.states, :name, :name %>
</td>
</tr>
<tr>
<td>
<%= f.label :issue_state_eq, 'Issue State is:' %>
<%= f.collection_select :issue_state_eq, LineItem.aasm(:issue_state).states, :name, :name %>
</td>
</tr>
<tr>
<td>
<%= f.label :invoice_state_eq, 'Invoice state is:' %>
<%= f.collection_select :invoice_state_eq, LineItem.aasm(:invoice_state).states, :name, :name %>
</td>
</tr>
<tr>
<td> <%= f.submit %>
</td>
</tr>
</tbody>
<% end %>
</table>
I will also add in the controller actions:
class LineItemsController < ApplicationController
include Pagy::Backend
def search
index
render :index
end
def index
@q = LineItem.ransack(params[:q])
if current_user.admin?
@pagy, @line_items = pagy(@q.result(distinct: true).order("quote_id DESC"))
else
@pagy, @line_items = pagy(@q.result(distinct: true).order("quote_id DESC"))
end
end
end
The key point to note is the use of the f.collection_select
helper method. This obviates the need to pass in a select
option to other types of view helper methods out there: the options_for_select
and options_from_collection_for_select
helper methods.