My scenario (running Rails 2.3.5):
On a department's products page (index.js.rjs), there is a table showing the products with their id, name, category. The view of this table is specified by a partial file called _index.html.erb. I'm going to add in a selection/option drop down menu above the table to show all the product categories. When the user selects a category from the drop down menu, Ajax kicks in such that the table (not the entire page) will be updated with just the products that have category equal to the selected category (i.e. a filtering operation).
File "_index.html.erb" has,
<table id='<%= dom_id(@department, :products) %>'>
<thead>
<tr>
<%= select_tag("filter_by_category",
options_from_collection_for_select(Categories.find(:all, :order => 'name'), :name, :name) %>
<%= observe_field("filter_by_category",
{ :url => department_products_path(:department_id => @department.id),
:method => :get,
:frequency => 0.5,
:with => "'filter_by_category=' + value" }) %>
</tr>
<tr> <td>id</td> <td>name</td> <td>category</td> </tr>
</thead>
<% @products.each do |product| %>
<%= render :partial => 'departments/product', :locals => {:product => product} %>
<% end %>
</table>
File "_product.html.erb" has,
<!-- for now, using some simplistic conditionals to do the filtering -->
<!-- filter_by_category is not set to the selected category name after a user selection -->
<% if :filter_by_category == product.category %>
<tr id='<%= dom_id(product) %>' >
<td><%= product.id %></td>
<td><%= product.name %></td>
<td><%= product.category %></td>
</tr>
<% end %>
Right now, when I select a category, nothing happens. The server log shows no activity at all.
The questions that I have:
Do I need a "no-op" form to enclose my table?
<% form_tag('javascript:void(0)') do %> <table> ... </table> <% end %>
Do I need onChange for the select_tag? The current HTML codes have this:
<select id="filter_by_category" name="filter_by_category" onChange="filter_by_category">.....
Does that mean I have to create a helper/controller for filter_by_category? If so, what should it contains? All I want is to refresh the table.
Do I need to specify more options for observe_field, such as update, etc.?
In "_product.html.erb" the "filter_by_category" is not set to the selected category name after a user selection.
Is there a better way to implement such kind of dynamic filtering?
What about using link_to_remote instead of observe_field? The user first selects the category, then clicks on the link_to_remote for the table to refresh. With this approach, I could at least make it to refresh the table. However, I still don't know how to capture/specify the selected value to be used in the partial for filtering purpose.
Any response to any of the questions is highly appreciated.
Hoca