Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: Filter index page and Re-display filter inputs
    primarykey
    data
    text
    <p>I am not sure what the proper Rails 3 way to do this is. I want to have filter criteria fields at the top of my index view that will filter the data.</p> <p>What I have below works for filtering my list, but I also want the filter fields to be re-populated with what the current filter is, and I can't figure out how to do that. The method I got working below also doesn't feel like the "right" way to accomplish this, since it relies on things like passing empty string to the field helper methods in my view.</p> <p>Controller:</p> <pre><code> def index @animals = Animal.by_color(params[':color']).by_age(params[':age']).paginate(:page =&gt; params[:page]) respond_to do |format| format.html # index.html.erb format.xml { render :xml =&gt; @animals } end </code></pre> <p>end</p> <p>View:</p> <pre><code>&lt;h1&gt;Listing Animals&lt;/h1&gt; Filter By: &lt;%= form_for(:animal, :url =&gt; { :action =&gt; "index" }, :html =&gt; {:method =&gt; :get} ) do |f| %&gt; &lt;div&gt; Color: &lt;%= text_field'', ':color', :size =&gt; 10 ) %&gt; Age: &lt;%= text_field('', ':age') %&gt; &lt;%= f.submit "Filter List" %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;%= will_paginate %&gt; ... </code></pre> <p>I am using the scope methods in my Model, which work very slick. I am just fuzzy about how the Controller "params" method and the View methods "form_for", "text_field" map to each other. Any ideas on how to refactor this and also get my filter fields populated when the list is currently filtered?</p> <h2>Solution!</h2> <p>Controller:</p> <pre><code>def index @search = Animal.new(params[:animal]) @animals = Animal.by_color(@search.color)... .... </code></pre> <p>View:</p> <pre><code>&lt;%= form_for(@search, :url =&gt; { :action =&gt; "index" }, :html =&gt; {:method =&gt; :get} ) do |f| %&gt; &lt;%= f.text_field(:color) </code></pre> <p>The form population works by creating the @search object in my contorller (in addition to my main animals object). Then using form_for to create a for around it.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload