我想按论坛帖子的数量按降序排列每个论坛。我的forum_posts_count
表格已经有Forum
列。
Forum.rb
class Forum < ActiveRecord::Base
scope :popular, -> { order("forum_posts_count DESC") }
has_many :forum_posts, through: :forum_threads
end
forums_controller.rb
ForumsController < ApplicationController
def index
@forums = Forum.all.popular
end
end
forum_post.rb Class ForumPost&lt;的ActiveRecord ::基
has_one :forum, through: :forum_thread
belongs_to :forum_thread, touch: true
after_create :increment_forum_posts_count
after_destroy :decrement_forum_posts_count
private
def increment_forum_posts_count
Forum.increment_counter( 'forum_posts_count', self.forum_thread.forum_id )
end
def decrement_forum_posts_count
Forum.decrement_counter( 'forum_posts_count', self.forum_thread.forum_id )
end
end
... add_counters_to_forums_table.rb(迁移)
class AddCountersToForumsTable < ActiveRecord::Migration
def self.up
change_table :forums do |t|
t.integer :forum_threads_count, :forum_posts_count, default: 0
end
Forum.reset_column_information
Forum.all.pluck(:id).each do |id|
Forum.reset_counters(id, :forum_posts)
Forum.reset_counters(id, :forum_threads)
end
end
def self.down
change_table :forums do |t|
t.remove :forum_threads_count, :forum_posts_count
end
end
end
我没有收到错误或任何错误,只是没有正确地订购论坛。这可能是缓存的问题吗?我已经重置了数据库,但它的订购仍然不正确。