2011-05-31 14 views
1

我用counter_cache來計算用戶的帖子號碼,但它不起作用。爲什麼counter_cache不起作用

#Post Model  
class Post < ActiveRecord::Base 
    belongs_to :user, :counter_cache => true 
end 

#User Model 
class User < ActiveRecord::Base 
    has_many :posts 
end 

有一個帖子表並以我的用戶表一個POSTS_COUNT

當我創建一個新的職位,該POSTS_COUNT不能算多少,只是停止0.Very奇怪problem.What上午我錯過了?

--------------------更多詳細信息------------------

我跟蹤創建動作:

User Load (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1 
SQL (0.0ms) BEGIN 
SQL (7.0ms) describe `posts`AREL (0.0ms)INSERT INTO `posts` (`user_id`, `title`, `content`, `created_at`, `updated_at`) VALUES (NULL, 'test', 'test','2011-06-01 07:29:10', '2011-06-01 07:29:10') 
SQL (54.0ms) COMMIT 
SQL (0.0ms) BEGIN 
AREL (1.0ms)UPDATE `posts` SET `user_id` = 1, `updated_at` = '2011-06-01 07:29:10' WHERE `posts`.`id` = 16[0m 
SQL (38.0ms) COMMIT 
Redirected to http://localhost:3000/user/post 
Completed 302 Found in 250ms 

--------------------- OK now ---------------- -----

在我的崗位科瑞操作:

#I change the following code 
#@post = Post.create(params[:post]) 
#@user.posts << @post 

@post = @user.posts.build(params[:post]) 
@post.save 
+0

你是如何創建帖子的?任何錯誤?這個帖子是否真的保存了? – 2011-05-31 09:21:46

+0

我通過Create Action @ post.save創建帖子,它創建成功。 – Xhinking 2011-05-31 09:26:18

回答

1

你應該知道,保存和創造是不同的,在與銷燬和刪除相同的方面。

保存和刪除不會經過任何回調,因此它不會更新緩存計數器。如果你想更新緩存計數器,你應該使用create。

+0

我用@post = Post.create(params [:post]),但它仍然不起作用。 – Xhinking 2011-05-31 09:59:36

+0

您是否檢查過數據庫,並確認該條目確實已保存? – 2011-05-31 10:31:20

+0

是的,我想也許我犯了一些愚蠢的錯誤,但是我找不到它。 – Xhinking 2011-05-31 10:36:21