![](/img/trans.png)
[英]Rails / Active Record has_many through association - fetching a record
[英]Rails/Active Record, Order by association / has_many count
我有一些書籍,他們可以通過另一個表格關聯許多主題。
class Book < ActiveRecord::Base
has_many :book_topics, dependent: :destroy
has_many :topics, through: :book_topics
end
然后,我有一個助手列出所有主題,但我想按具有該主題的書籍數量列出要排序的主題。
我嘗試了以下方法的變體:
def topic_list
Topic.joins(:book_topics)
.group("book_topics.topic_id")
.order("count(book_topics.book_id) desc")
end
沒有運氣。
認為執行此操作的正確方法是實現計數器緩存
在book_topic.rb中,您將擁有
class BookTopic < ActiveRecord::Base
belongs_to :topic, counter_cache: true
end
topic.rb應該保持不變
class Topic < ActiveRecord::Base
has_many :book_topics, dependent: :destroy
end
但是,您必須將計數器列添加到主題表
class AddBookTopicsCountToTopics < ActiveRecord::Migration
def change
add_column :topics, :book_topics_count, :integer, default: 0
end
end
遷移它,如果您已有記錄,則更新counter val,從那里可以輕松按主題的書數對主題進行排序。
我意識到您想要查詢來解決此問題,但是以我的經驗,這應該更快。
抱歉,如果有錯誤。 計數器名稱不是最好的,但是在文檔中有一個示例如何更改它。 如果還不夠的話,還有一個railscast vid。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.