views:

84

answers:

3

I have a standard master-detail relationship between two models in a RoR application. The detail records contain four boolean fields indicating presence / absence of something.

When I display the detail records I want to add a summary indicating the number of records which have their boolean value set to True for each of the four boolean fields.

For example: Date | Boolean Field 1 | Boolean Field 2 | etc 2009/08/29 | T | T | 2009/08/30 | T | F | 2009/08/31 | F | T | 2009/09/01 | F | T |

Total: 4 2 3

I tried using something like @entries.count(["Boolean Field 1", true]) The way I see it, there are two ways to calculate these values: one at the model by executing an SQL query (ugly) or at the view level by using a counter (ugly again.) Is there some other way to achieve what I want?

Thank you for your time,

Angelos Arampatzis

+1  A: 

May be

@entries.select {|r| r.bool_field1}.size
dimus
A: 

sql isn't as ugly as rails makes it out to be and it is rather efficient, just make it a named_scope and your controller/view will still look pretty

ErsatzRyan
+1  A: 

You can either do:

@entries.count(:conditions => { :boolean_field_1 => true })

You can pretty this up by doing a named scope:

named_scope :booleans,  :conditions => { :boolean_field_1 => true })

and then

@entries.booleans.count

Or if you already have ALL the items in an array (rather than a select few) and do not want to hit the database…

Rails provides a ? method for all columns. So while you have:

@entry.boolean_field

You also have:

@entry.boolean_field?

So you can do this:

@entries.collect(&:boolean_field?).length
Pie