Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a rails form to filter an index page?

G'day guys, I'm having an issue with filtering the presentation of several thousand trade items I have in my system. As per the specs of the system we're building we have to have a form that allows people to put in a start date and then an interval in minutes, to filter the presentation of the items. I've built my helper functions to return all of the trades within that interval period, but I can't for the life of me properly build the form that will return a dateTime value and an integer value within the top of the index page?

Any ideas? Would I have to build a separate model object to assign values to, or is there a simpler way?

like image 268
Schroedinger Avatar asked Apr 24 '10 04:04

Schroedinger


2 Answers

On your index page you can create a filter form like this

<%= form_tag '', :method => :get do %>
  <%= text_field_tag :value_one %>
  <%= text_field_tag :value_two %>
  <%= submit_tag 'Filter' %>
<% end %>

Your form will then do a GET on your page with query string parameters and then in your controller you can look for the filter parameters that might have been passed.

like image 70
Corey Avatar answered Sep 28 '22 04:09

Corey


I like gradually building a filter in my controller, ie:

def index

  filter = []

  if params.has_key?("filter")

    if !params[:filter][:user_id].blank?
      id = params[:filter][:user_id]
      filter << ["user_id = #{id.to_i}"]
    end

    if !params[:filter][:project_id].blank?
      id = params[:filter][:project_id]
      filter << ["project_id = #{id.to_i}"]
    end

    if !params[:filter][:change_type_id].blank?
      id = params[:filter][:change_type_id]
      filter << ["change_type_id = #{id.to_i}"]
    end

  end

  @logs = LogEntry.where(filter.join(" AND ")).order('created_at DESC')    

end

If no filter is selected in your view (I use the select_tag form helper), your DB query will return all records.

like image 23
Nick DiZazzo Avatar answered Sep 28 '22 04:09

Nick DiZazzo