Ransack sort on count of HABTM or HMT associated records

会有一股神秘感。 提交于 2019-11-26 23:33:50

问题


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.


回答1:


Given you have your entities queried with the above scope, for example your index query always has:

# controller
@search = Theme.ransack(params[:q])
@themes = @search.result(distinct: true).with_quotes_count

Have a try of:

# model
ransacker :quotes_count_sort do
    Arel.sql('quotes_count')
end

And use the name of the sort in sort_link?




回答2:


there is some patch that could be helpful for you to use scope Visit https://gist.github.com/ledermann/4135215



来源:https://stackoverflow.com/questions/41984939/ransack-sort-on-count-of-habtm-or-hmt-associated-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!