Justin
Justin

Reputation: 1956

How to Create a Rails Dropdown Filter

I am trying to create a dropdown filter in Rails 3.2.

I have seen solutions along these lines, but am unsure about how to implement them in my case. Filter results on index page from dropdown.

I have a table of events and I'd like a dropdown box to filter those events by category. I am half way there by doing something along these lines in the view using params:

<% @event.events_by_category(sanitize_output(params[:cat])).each do |e| %>
  ...
<% end %>

And then using the following in the event model:

def self.events_by_category(cat)
  if cat == nil
    all
  else
    where("category = ?", cat)
  end
end

However, creating a dropdown that refreshes the URL to include params in jQuery seems very dirty.

What's the best way to accomplish this type of dropdown in Rails?

Upvotes: 1

Views: 5001

Answers (1)

Justin
Justin

Reputation: 1956

You can use form_tag for this:

<%= form_tag events_path, method: 'get' do %>
  <%= select_tag :cat, Options::TYPE %>
  <%= submit_tag 'Filter' %>
<% end %>

Upvotes: 1

Related Questions