Search code examples
ruby-on-railsarel

Rails Arel, counting value of an include?


I am mostly used to writing plain sql for things but I would like to understand arel better. Basically what can I do to count the contents of an :include.

Category.includes(:discussions)

That is my include then discussions has_many comments. I need to know how to count the comments of the category model.

Sorry if this is blatantly obvious and thanks for any help in advance!

Edit: Updated for count on category not discussion.


Solution

  • I'm far from an Arel expert, but my instinct as that you have to get at least a little bit manual in your calculations. Here is how you can get the count for each category making maximal use of arel:

    Category.joins(:discussions => :comments).group('categories.id').select('categories.id, COUNT(*) as cnt')
    

    Note that you won't have the full model for categories loaded, but I think this is the fastest way to get the full list of counts. I'm not sure what other approaches you could take with arel, but I think this is the fastest query. Depending your specific application you might want to do things a bit differently.