views:

65

answers:

1

Hello,

I'm attempting to create a filter on a rails application that uses multiple check boxes corresponding to one db-column/attribute to filter through results, but I'm not sure how to go about it exactly.

EX.
index shows a list of the last few years' weather and you want to filter through it
These attributes would be part of a Day class.

View
<fieldset>
<legend>Sky</legend>
<%= check_box_tag('filter[sky][]', 'sunny') %>Sunny
<%= check_box_tag('filter[sky][]', 'partly sunny') %>Partly Sunny
<%= check_box_tag('filter[sky][]', 'overcast') %>Overcast
</fieldset>
<fieldset>
<legend>Humidity</legend>
<%= check_box_tag('filter[humidity][]', 'low') %>Low
<%= check_box_tag('filter[humidity][]', 'average') %>Average
<%= check_box_tag('filter[humidity][]', 'high') %>High
</fieldset>
`

I want to then be able to go through the options for each filter and apply all that have been selected. So if I want to see all days that were sunny with low and average humidity, I would check those boxes and get days that were summy with either low humidity or average humidity. SQL wise we'd be talking an IN clause.

I'm pretty new to rails so I'm not sure if there's some special rails functionality I should use for this or not. Do I just need to write a function to run through the check boxes and build the SQL statement?

Any help is greatly appreciated. I will edit this post if I need to in order to clarify anything.

A: 

Depends on the version of Rails you're on, but I would suggest you look into dynamic scopes:

http://ryandaigle.com/articles/2008/12/29/what-s-new-in-edge-rails-dynamic-scope-methods

If named scopes are completely new to you, you should probably read the article linked from that page in the second paragraph (just after the first code snippet).

What you're suggesting is very slightly more complex because of the fact you want to be able to OR within sky and humidity and then AND those together, but nothing 20 minutes of tinkering won't produce a result for - I think you'll benefit from going through the exercise yourself though if you're new to Rails (if I'm wrong, say so :-) ).

p7r