我正在使用Ruby on Rails 3.2.2,我想設置一個計數器緩存值爲「自定義」。也就是說,在這個時候(在我的移民文件),我嘗試使用下面的代碼:如何將計數器緩存值設置爲給定值?
def up
add_column :articles, :comments_count, :integer, :default => 0
Article.reset_column_information
Article.find_each do |article|
# Note: The following code doesn't work (when I migrate the database it
# raises the error "comments_count is marked as readonly").
Article.update_column(:comments_count, article.custom_comments.count)
end
end
換句話說,我想設置:comments_count
值(計數器緩存數據庫表列) 爲自定義值(在我的情況該值article.custom_comments.count
- 注:該custom_comments
不是一個ActiveRecord協會,但在Article
模型類規定的方法,它返回一個整數值爲好)是不與has_many
關聯有關秒。
也許,我可以/應該使用類似
Article.reset_column_information
Article.find_each do |article|
Article.reset_counters(article.id, ...)
end
但似乎reset_counters
方法離不開has_many
協會工作。
如何將:comments_count
計數器緩存值設置爲與「自定義關聯」相關的給定值?
計數器緩存的問題是它使用默認範圍。這意味着如果你想計算一些孩子被軟刪除的東西,計數就會是0.然後當你恢復這個對象時,大概你會恢復孩子們。但計數器緩存仍然是0。 – Mohamad