counter_cache 实现的问题 [英] Problem with counter_cache implementation
问题描述
我正在'rake 中止!...posts_count 被标记为只读错误.
I'm getting 'rake aborted! ... posts_count is marked readonly' errors.
我有两个模型:user 和 post.
I have two models: user and post.
users has_many posts.
posts belongs_to :user, :counter_cache => true
我有一个迁移,将 posts_count 列添加到 users 表,然后计算并记录每个用户的当前帖子数.
I have a migration which adds the posts_count column to the users table and then calculates and records the current number of posts per user.
self.up
add_column :users, :posts_count, :integer, :default => 0
User.reset_column_information
User.all.each do |u|
u.update_attribute( :posts_count, u.posts.count)
end
end
运行迁移时出现错误.当然,这是非常明确的,如果我从帖子模型中删除 :counter_cache 声明,例如
when I run the migration I get the error. This is pretty clear-cut, of course and if I remove the :counter_cache declaration from the posts model, e.g.
belongs_to :user
迁移运行良好.这显然没有意义,因为您无法以这种方式真正实现它.我错过了什么?
the migration runs fine. This obviously, does not make sense because you couldn't really implement it this way. What am I missing?
推荐答案
您应该使用 User.reset_counters
来执行此操作.此外,我建议使用 find_each
而不是 each
因为它会分批迭代集合,而不是一次迭代所有.
You should be using User.reset_counters
to do this. Additionally, I would recommend using find_each
instead of each
because it will iterate the collection in batches instead of all at once.
self.up
add_column :users, :posts_count, :integer, :default => 0
User.reset_column_information
User.find_each do |u|
User.reset_counters u.id, :posts
end
end
这篇关于counter_cache 实现的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!