Schroedinger
Schroedinger

Reputation: 1283

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?

Upvotes: 6

Views: 8715

Answers (2)

Corey
Corey

Reputation: 2243

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.

Upvotes: 16

Nick DiZazzo
Nick DiZazzo

Reputation: 73

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.

Upvotes: 2

Related Questions