I have a HABTM relationship between the Theme
and Quote
models. The themes
index
view displays the count of quotes associated with each theme. I'd like to add a Ransack sort_link
on that column, so the themes
can be sorted by their count of associated quotes
.
I have done this successfully with has_many
associations using a counter cache column, but Rails does not support counter cache columns for HABTM associations.
So far, I've got a scope that adds a virtual attribute called quotes_count
(by performing a single query, avoiding N+1) to the Theme
model:
scope :with_quotes_count, -> do
joins('LEFT OUTER JOIN quotes_themes on quotes_themes.theme_id = themes.id')
.select('themes.*, COUNT(quotes_themes.quote_id) as quotes_count')
.group('themes.id')
end
Seems like I have to convert the above scope into a "Ransacker" using ARel but so far all my attempts have failed.
I'm using Rails 4.2.2, ARel 6.0.4 and PostgreSQL 9.5.4.
Any help will be greatly appreciated.