Carvefx
Carvefx

Reputation: 448

Count DIFFERENT results in a rails find call

Let's suppose I have a model with only two fields: name and street name.

How would I find out the number of different *street names* in a controller method?

Upvotes: 3

Views: 196

Answers (3)

leflings
leflings

Reputation: 646

This will return the total number of different street_names

Model.group(:street_name).all.count

This will return an ordered hash with a count of names on each street

Model.group(:street_name).count

Upvotes: 4

krunal shah
krunal shah

Reputation: 16339

Try this !

Model.find(:all,:select => 'DISTINCT street_name').size

Upvotes: 3

0x26res
0x26res

Reputation: 13922

why don't you do a 'count_by_sql' where you would use the request select count(*) from (select distinct(street_name) from <table_name>)

Otherwhise you can do it in ruby: <ModelName>.all.group_by(&:street_name).size

Upvotes: 3

Related Questions