Ruby on Rails 计数器缓存错误
当尝试在我的 RoR 应用程序中实现计数器缓存列时,我收到错误Unknown key(s): counter_cache
。
我在这个问题中实现了模型关联:模型关联问题
这是我的迁移:
class AddVideoVotesCountToVideos < ActiveRecord::Migration
def self.up
add_column :videos, :video_votes_count, :integer, :default => 0
Video.reset_column_information
Video.find(:all).each do |p|
p.update_attributes :videos_votes_count, p.video_votes.length
end
end
def self.down
remove_column :videos, :video_votes_count
end
end
但是,观看http://media.railscasts.com/videos/023_counter_cache_column.mov后我我想也许我必须移动 :counter_cache => true
在 belongs_to :video
之后进入 VideoVote 模型。但是,当我这样做时,我收到错误:
参数数量错误(2 为 1)
我做错了什么?
I get the error Unknown key(s): counter_cache
when trying to implement a counter cache column in my RoR app.
I implemented the model associations in this question: Model association question
Here's my migration:
class AddVideoVotesCountToVideos < ActiveRecord::Migration
def self.up
add_column :videos, :video_votes_count, :integer, :default => 0
Video.reset_column_information
Video.find(:all).each do |p|
p.update_attributes :videos_votes_count, p.video_votes.length
end
end
def self.down
remove_column :videos, :video_votes_count
end
end
However, after watching http://media.railscasts.com/videos/023_counter_cache_column.mov I thought that maybe I had to move :counter_cache => true
into the VideoVote model after belongs_to :video
. However, when I do that, I get the error:
wrong number of arguments (2 for 1)
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
update_attribute
不是update_attributeS
或使用
update_attributes
:UPD 1
:counter_cache => true
应该位于 VideoVote 类中:update_attribute
notupdate_attribteS
or with
update_attributes
:UPD 1
:counter_cache => true
should be at the VideoVote class:要执行 counter_caching,您需要先运行填充计数列的迁移,然后再将 counter_cache 语句包含在模型中。一旦进入模型,这些列就是只读的。
To do counter_caching,you need to run the migration first that fills in the count columns BEFORE you include the counter_cache statement in the model. Once in the model, the columns are read only.
为了避免运行此迁移时出现只读错误,您应该使用reset_counters:
To avoid read-only errors while running this migration, you should use reset_counters:
重写 Rajive Jain 的解决方案:
删除
:counter_cache => true
模型文件中的语句。重新运行迁移:
rake db:migrate
在模型中添加 counter_cache 语句:
:counter_cache =>正确
Rewriting Rajive Jain's solution :
Remove
:counter_cache => true
statement from the model file.Rerun the migration :
rake db:migrate
Add the counter_cache statement in your model :
:counter_cache => true