Skip to content

Creating a search form

joekur edited this page Feb 7, 2013 · 1 revision

For this example, imagine we have a User record that we want to display in a table with zable. We'll give it a couple attributes with default sorting and searching.

# user.rb
class User < ActiveRecord::Base
  attr_accessible :name, :email
  sortable :name, :email
  searchable :name, :email
end

Remember, the default searchable behavior allows us to do equality based searching on the given attributes. If you want to do something more complicated, you can also create a custom named scope.

In our view, we'll create the table:

-# users/index.html.haml

= zable @users do
  - column(:name)
  - column(:email)

Now we'll make a form that allows us to search on either name or email. This form will send a GET request to the current route along with the user's inputted search terms.

-# users/index.html.haml

= form_tag current_url, method: :get do
  = text_field_tag 'search[name]', params[:search] && params[:search][:name]
  = text_field_tag 'search[email]', params[:search] && params[:search][:email]
  = zable_hidden_search_fields
  = submit_tag "Search" 

A couple notes here:

  • current_url is provided by the zable gem. You could of course use any path you want.
  • The name of each input should follow the form "search[#{attr}]". We are also grabbing these params for the value of each input so that you can see what you searched for after you submit the form.
  • zable_hidden_search_fields is a provided helper to inject hidden fields into the form to preserve any sort or pagination state you may have.

Let's say you also want a 'show all' button to reset any search paramaters. You could just have a link to the current url, but that would also reset your other states (sort, pagination). The easiest way to do this would be another form with no search inputs:

-# users/index.html.haml

= form_tag current_url, method: :get do
  = zable_hidden_search_fields
  = submit_tag "Show All Users"
Clone this wiki locally