簡體   English   中英

Rails 3,通過鏈接模型可排序的表列?

[英]Rails 3, Sortable table columns by linked models?

我最近在關注http://railscasts.com/episodes/228-sortable-table-columns ,將可排序的表格列添加到我的應用中。 效果很好,但是我表中的某些列是諸如post.comments.count之類的(顯然,帖子有很多注釋)。 我希望能夠按表中帖子的評論數進行排序,但是我無法弄清楚如何使用railscast中的解決方案來實現此目的。

最簡單的方法是使用counter_cache

使用遷移,在表posts上創建一個comments_count:integer數據庫字段。

然后更新您的模型:

class Comment < ActiveRecord::Base
  belongs_to :post, :counter_cache => true
end

然后在該列上排序:

Post.order(:comments_count)

在您提到的情況下,一種方法是計數器緩存列

post.comments_count 
# instead of 
post.comments.count

不知道這是否適用於您的每種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM