开发者

Why counter_cache doesn't work

开发者 https://www.devze.com 2023-03-09 04:28 出处:网络
I used counter_cache to count the User\'s posts number, but it doesn\'t work. #Post Model class Post < ActiveRecord::Base

I used counter_cache to count the User's posts number, but it doesn't work.

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

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

There are a Posts Table and also a posts_count in my Users Table

When I create a new post,the posts_count can't count the number,just stop 0.Very strange problem.What am I missing?

--------------------More detail------------------

I track the create action:

User Load (0.0ms) SELECT `users`.* FROM `u开发者_高级运维sers` 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---------------------

In my Post Creat Action:

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

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


You should know that save and create are different, in the same respect as destroy and delete.

Save and delete won't go through any callbacks, so it won't update the cache counter. You should use create, if you want to update the cache counter.

0

精彩评论

暂无评论...
验证码 换一张
取 消