【问题标题】:Ruby on Rails counter cache errorRuby on Rails 计数器缓存错误
【发布时间】:2011-03-17 19:12:55
【问题描述】:

尝试在我的 RoR 应用中实现计数器缓存列时收到错误 Unknown key(s): counter_cache

我在这个问题中实现了模型关联:Model association question

这是我的迁移:

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 之后,我想也许我必须在belongs_to :video 之后将:counter_cache =&gt; true 移动到VideoVote 模型中。但是,当我这样做时,我得到了错误:

wrong number of arguments (2 for 1)

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 associations counter-cache


    【解决方案1】:

    update_attribute 不是update_attribteS

    p.update_attribute :videos_votes_count, p.video_votes.length
    

    update_attributes:

    p.update_attributes( :video_votes_count => p.video_votes.length )
    

    UPD 1

    :counter_cache =&gt; true 应该在 VideoVote 类中:

    class VideoVote < ActiveRecord::Base
      belongs_to :user
      belongs_to :video, :counter_cache => true
    end
    

    【讨论】:

    • 仍然出现第一个错误...:counter_cache =&gt; true 应该去哪里?
    • 好的,现在我收到这个错误:undefined method 'videos_votes_count=' for #&lt;Video:0x10362a698&gt;
    • 您使用update_attributesupdate_attribute?您也可以临时删除counter_cache =&gt; true,因为它显然会锁定字段
    • 你使用什么方法,update_attributesupdate_attribute 是哪一种? :) 并删除 counter_cache =&gt; true 一段时间,进行迁移并将其返回 :)
    • 啊,好的,解决了,我需要取出 counter_cache,迁移,然后返回...谢谢!
    【解决方案2】:

    要执行 counter_caching,您需要先运行填充计数列的迁移,然后再将 counter_cache 语句包含在模型中。进入模型后,这些列是只读的。

    【讨论】:

      【解决方案3】:

      为避免在运行此迁移时出现只读错误,您应该使用 reset_counters:

      Video.find_each do |video|
        Video.reset_counters video.id, :video_votes
      end
      

      【讨论】:

      • reset_counters方法的第二个参数需要是关联的名称,而不是counter_cache列的名称,所以应该是:Video.reset_counters video.id, :video_votes
      • 感谢@AndreaSingh!已更新。
      • reset_counters 现已弃用
      【解决方案4】:

      重写 Rajive Jain 的解决方案:

      从模型文件中删除:counter_cache =&gt; true 语句。

      重新运行迁移:rake db:migrate

      在模型中添加 counter_cache 语句::counter_cache =&gt; true

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-24
        • 2013-09-25
        • 1970-01-01
        • 2015-01-30
        • 1970-01-01
        • 2011-01-28
        相关资源
        最近更新 更多