activerecord - rails: count and group with joined tables -


i have following models:

car:  has_many :car_classes    carclass: belongs_to :car belongs_to :carmainclass  carmainclass: has_many :car_classes 

what want count amount of cars in carclass grouped car_main_class_id linked main_class_symbol in carmainclass.

the query have is:

carclass.group(:car_main_class_id).count(:car_id) => {43=>79, 45=>4 ...} 

which want, except end :car_main_class_id :main_class_symbol carmainclass:

{"a1"=>79, "a2"=>4 ...} 

i tried joining tables , custom select options, didn't work.

can done in query in don't have iterate through main classes again?

many help!

instead of having sql approach , using "count/group by", should simple feature of rails activerecords : counter_cache column.

for example, can add column "car_classes_count" in carmainclass, , in carclass class, :

carclass: belongs_to :car belongs_to :car_main_class, :counter_cache => true 

you can same column "car_class_count" in car.

i don't know if can help, had same kind of problems when started develop rails. tried unsuccessful crazy sql queries (queries worked w/ sqlite, did not w/ postgres) , choose other approach.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -