Habtm Associations In Rails : Collecting And Counting The Categories Of A Model's Children
Solution 1:
Provided that you have a books_categories join table you can add a has_many :categories, through: :books association to which links stores and categories through books.
classStore < ActiveRecord::Base
has_many :books
has_many :categories, through::booksendThat's the easy part. Now lets get each category and the books count (revised):
def books_per_category
categories.select('categories.id, categories.name, count(books.id) as count')
.group('categories.id, categories.name')
.map do |c|
{
name: c.name,
count: c.count
}
endendCourtesy of @jakub-kosiĆski
Solution 2:
Generally, instead of using Rails' built-in 'has_and_belongs_to_many' method, it is better practice to use a join table. In this setup, you have three tables:
- Books
- Categories
- BookCategories
The BookCategories (or whatever you decide to call it) is a join table that belongs_to both Books and Categories and has a Foreign ID of each. You would then use Rails' "has_many :through" to link the Books and Categories.
The store would have a 'has_many' relationship with books. With the prior relationship setup right, you can then use this method to get the count for a store for a particular category:
Store.books.where(category:'Mystery')
Post a Comment for "Habtm Associations In Rails : Collecting And Counting The Categories Of A Model's Children"