I'm not sure if this is the correct way to Rails 3. I want to have filter criteria fields at the top of my index view that will filter the data.
What I have below works to filter my list, but I also want the filter fields to be re-populated using the current filter, and I cannot figure out how to do this. The method I got below also doesn't look like the โrightโ way to do this, since it relies on things like passing an empty string to auxiliary field methods in my opinion.
Controller:
def index @animals = Animal.by_color(params[':color']).by_age(params[':age']).paginate(:page => params[:page]) respond_to do |format| format.html
end
View:
<h1>Listing Animals</h1> Filter By: <%= form_for(:animal, :url => { :action => "index" }, :html => {:method => :get} ) do |f| %> <div> Color: <%= text_field'', ':color', :size => 10 ) %> Age: <%= text_field('', ':age') %> <%= f.submit "Filter List" %> </div> <% end %> <%= will_paginate %> ...
I use scope methods in my model that work very smoothly. I'm just vague about how the params method of the controller and the View methods "form_for", "text_field" match each other. Any ideas on how to reorganize this, as well as get the filter fields currently filled in while filtering?
Decision
Controller:
def index @search = Animal.new(params[:animal]) @animals = Animal.by_color(@search.color)... ....
View:
<%= form_for(@search, :url => { :action => "index" }, :html => {:method => :get} ) do |f| %> <%= f.text_field(:color)
The population of the form works by creating an @search object in my contorller (in addition to my main animal object). Then use form_for to create around it.
source share