mardi 8 décembre 2015

ruby number of string value occurrences for distinct another column value

I have a model Counter which returns the following records

name.....flowers.....counter  
vino.....rose.........1
vino.....lily.........1 
gaya.....rose.........1 
rosi.....lily.........1 
vino.....lily.........1 
rosi.....rose.........1 
rosi.....rose.........1 

I want to display in the table like

name | Rose | Lily |
---------------------
Vino |  1   | 2    |
---------------------
Gaya |  1   | 0    |
---------------------
Rosi |  2   | 1    |

I want to display the count of flowers for each distinct name. I have tried the following and wondering how can I do it elegantly?

def counter_results
  @counter_results= {}
  Counter.each do |name|
    rose = Counter.where(flower: 'rose').count
    lily= Counter.where(flower: 'lily').count
    @counter_results['name'] = name
    @counter_results['rose_count'] = rose
    @counter_results['lily_count'] = lily
  end
  return @counter_results
end

which I dont get the hash values.

Aucun commentaire:

Enregistrer un commentaire