Forum: Ruby on Rails How do I bind a form to filter a table?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
sa 1. (Guest)
on 2008-12-25 16:19
Hi - I'm trying to enable dynamic filtering of a table in my app, using
selection lists and a search box. Here's the basic layout of the table:

# -------------------
# in app/views/products/index.html.erb

<div id="filters">
  <%= select :product,
             :vendor_id,
             Vendor.find(:all, :order => 'name').collect {|v| [v.name,
v.id] },
             :prompt => 'select vendor' %>
  <%= text_field_tag 'query', params['query'] %>
</div>

<table id="ptable">
  <tr>
    <th>Product</th>
    <th>Vendor</th>
    <th>Stocked?</th>
  </tr>
  <%= render :partial => 'product', :collection => @products %>
</table>

<% observe_field 'query', :update => 'ptable', :url => { :action =>
'filter' },
                           :with => 'query' }

# -------------------
# in app/views/products/_product.html.erb
<tr>
  <td><%=h product.name %></td>
  <td><%=h product.vendor.name %></td>
  <td>
     <% if product.stocked? %>
       YES
     <% else %>
       NO
     <% end %>
  </td>
</tr>


# -------------------
# in app/controllers/product_controller.rb

def filter
  cond = ["name LIKE ?", "%#{params[:query]%"] unless
params[:query].nil?
  @products = Product.find(:all, :conditions => cond)
  render :partial => 'product', :collection => @products if
request.xml_http_request?
end

(this is based on a great tutorial found at
http://dev.nozav.org/rails_ajax_table.html)

So far I only got the text box to respond filter the table, and even
there my header row disappears when I do that.

So, instead of observe_field I thought of using observe_form and tying
my controls in a remote_form_for so that I could call the 'filter'
action with the changes. I played with it for a while and couldn't get
it to work, mostly because I'm not sure how to construct my
remote_form_for block with current controls (I try
form_remote_for(@product) but get an :id error), and also don't know how
I can send all the parameters to the filter action.

Another question is more about staying DRY - how can I generalize this
solution so that I could reuse it throughout my app with multiple tables
(instead of adding filter action to every controller).

I would really be grateful for any help.
This topic is locked and can not be replied to.