Using TempObject with a search form

Here is how I use TempObject with a search form.

I’ll use an example of creating a form to return balls. In the controller I first create a TempObject with the attributes I want to offer in the search form:

@ball_search = TempObject.new(:colour, :size)

I can then use standard Rails form helpers to create the search form within a view:

<% form_tag do %>
  <p>Colour:  <%= text_field 'ball_search', 'colour' -%></p>
  <p>Size:  <%= text_field 'ball_search', 'size' -%></p>
  <p><%= submit_tag("Search for balls") -%></p>
<% end %>

It is then easy to gather the data passed from the form and load the @ball_search object with it by adding this line into the controller (below the statement creating the object):

@ball_search.load_data(params[:ball_search]) if params[:ball_search]

The data can then be used to find the balls with these attributes:

Ball.find(:all, 
  :conditions => ["colour = ? AND size = ?",
          @ball_search.colour,
          @ball_search.size])

This is a simple example, where I’ve just used text_field form helpers, but it works just as well with the other standard Rails form helper elements.

You can also use @ball_search.attribute_names to create the find conditions:

search_query = Array.new
search_data = Array.new
for name in @ball_search.attribute_names
  search_query << "#{namd} = ?"
  search_data << @ball_search.send(name)
end
Ball.find(:all, 
  :conditions => [search_query.join(" AND "), 
          search_data].flatten)

With that solution, if another search criteria needs to be added, all that is needed is to add the extra criteria to the original object creation statement and then add the extra form field.

controller:

@ball_search = TempObject.new(:colour, :size, :sport)

view:

<% form_tag do %>
  <p>Colour:  <%= text_field 'ball_search', 'colour' -%></p>
  <p>Size:  <%= text_field 'ball_search', 'size' -%></p>
  <p>Sport:  <%= text_field 'ball_search', 'sport' -%></p>
  <p><%= submit_tag("Search for balls") -%></p>
<% end %>

The code to gather all the data together and populate the find query remains the same.

This entry was posted in Ruby. Bookmark the permalink.