我已將forum_threads_count
和forum_posts_count
列添加到論壇表中。 forum_threads_count
工作得很好。 forum_posts_count
已重置爲「0」,而不是顯示在添加計數器緩存列之前創建的所有論壇帖子。關係如下:Forum has_many :forum_threads
,ForumThreads has_many:forum_posts和Forum has_many :forum_posts, through: :forum_threads
。Rails 4:使用counter_cache時,計數器顯示「0」而不是實際「大小」
我後來發現我無法使用與has_many through:
關係的counter_cache。所以我寫了一些私人方法來增加after_create
/after_destroy
調用來增加/減少計數器。該計數器的工作原理,只是它沒有考慮將這些列添加到論壇表之前創建的所有論壇帖子。我覺得我寫這個遷移的方式有點不對勁。請提前幫助並感謝您。我很感謝這個網站上的所有人幫助別人。
「...... add_counters_to_forums_table.rb」(遷移文件)
class AddCountersToForumsTableAgain < 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
型號/ forum.rb
class Forum < ActiveRecord::Base
has_many :forum_threads, -> { order ('updated_at DESC') }, dependent: :destroy
accepts_nested_attributes_for :forum_threads
has_many :forum_posts, through: :forum_threads
accepts_nested_attributes_for :forum_posts
end
型號/ forum_thread.rb
class ForumThread < ActiveRecord::Base
belongs_to :user
belongs_to :forum, counter_cache: true
has_many :forum_posts, dependent: :destroy
accepts_nested_attributes_for :forum_posts
end
個
型號/ forum_post.rb
class ForumPost < ActiveRecord::Base
belongs_to :forum_thread, touch: true
belongs_to :forum
belongs_to :user
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
的意見/論壇/ index.html.erb
<%= render 'shared/page_title', title: "Forums" %>
<div class="col-md-10 col-md-offset-1">
<div class="actions">
<%= link_to "Create New Forum", new_forum_path, class: 'btn btn-primary' %>
<div class="pull-right">
<%= form_tag @forum_thread, method: :get do |f| %>
<%= text_field_tag :q, nil, class: 'form-control', placeholder: 'Search...' %>
<% end %>
</div>
</div>
# LIST FORUMS WITH THREADS AND POSTS COUNTER CACHE
<div class="list-group">
<% @forums.each do |forum| %>
<a href="<%= forum_forum_threads_path(forum.id, @forum_threads) %>" class="list-group-item">
<h3><%= forum.title %>
<div class="pull-right small">
<%= pluralize forum.forum_threads.size, 'thread' %> |
<%= pluralize forum.forum_posts.size, 'post' %>
</div>
</h3>
</a>
<% end %>
</div>
我還是比較新的鐵軌。我正在使用Rails 4.2.1。我將如何去下載最新的穩定版本?另外,我遵循[本教程](http://www.eyupatis.com/rails-has-many-through-association-with-counter-cache-argument/),forum_posts_count返回了forum_threads的數量而不是forum_posts。 @phoet – BB123