mardi 29 décembre 2015

Rails has_many sums and counts with ActiveRecord

I've got a dilemma I think I may have coded myself into a corner over. Here's the setup.

My site has users. Each user has a collection of stories that they post. And each story has a collection of comments from other users.

I want to display on the User's page, a count of the total number of comments from other users.

So a User has_many Stories, and a Story has_many comments.

What I tried was loading all the users stories in @stories and then displaying @stories.comments.count, but I get undefined method 'comments' when I try to do that. Is there an efficient ActiveRecord way to do this?

Aucun commentaire:

Enregistrer un commentaire