[英]Rails/Active Record, Order by association / has_many count
I have a collection of books and they can have many topics associated through another table. 我有一些书籍,他们可以通过另一个表格关联许多主题。
class Book < ActiveRecord::Base
has_many :book_topics, dependent: :destroy
has_many :topics, through: :book_topics
end
Then I have a helper to list out all the topics, but I want to list topics to be ordered by the number of books that have that topic. 然后,我有一个助手列出所有主题,但我想按具有该主题的书籍数量列出要排序的主题。
I've tried variations of: 我尝试了以下方法的变体:
def topic_list
Topic.joins(:book_topics)
.group("book_topics.topic_id")
.order("count(book_topics.book_id) desc")
end
With no luck. 没有运气。
Think that proper way to do this would be to implement counter cache 认为执行此操作的正确方法是实现计数器缓存
in book_topic.rb you would have 在book_topic.rb中,您将拥有
class BookTopic < ActiveRecord::Base
belongs_to :topic, counter_cache: true
end
topic.rb should stay the same topic.rb应该保持不变
class Topic < ActiveRecord::Base
has_many :book_topics, dependent: :destroy
end
however, you would have to add the counter column to the topics table 但是,您必须将计数器列添加到主题表
class AddBookTopicsCountToTopics < ActiveRecord::Migration
def change
add_column :topics, :book_topics_count, :integer, default: 0
end
end
migrate it, update counter val if you have existing records, and from there it should be easy to sort topics by the number of books they have. 迁移它,如果您已有记录,则更新counter val,从那里可以轻松按主题的书数对主题进行排序。
i realize you want a query to solve this, but in my experience this should be much faster. 我意识到您想要查询来解决此问题,但是以我的经验,这应该更快。
sry if there are mistakes. 抱歉,如果有错误。 counter name is not the best, but there's an example in the docs how to change it.
计数器名称不是最好的,但是在文档中有一个示例如何更改它。 if it's not enough there's also a railscast vid.
如果还不够的话,还有一个railscast vid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.