【问题标题】:counter_cache with has_many带有 has_many 的 counter_cache
【发布时间】:2012-07-04 21:58:18
【问题描述】:

我读过这是不可能的,然后其他人告诉我这是不可能的。他们给了我这段代码,但后来不得不离开,现在我的应用程序坏了,直到我让它工作:/

我有一个标签模型,每个标签都有_many资源:通过=>资源标签。每个资源也有_many标签。

我需要知道每个标签拥有的资源数量(我不关心其他方式)。

问题是它说 unkown key cache_counter

这是我的模特

标签.rb

  has_many :resource_tags, :dependent => :destroy, :counter_cache => :resource_count
  has_many :resources, :through => :resource_tags

资源.rb

  has_many :resource_tags, :dependent => :destroy
  has_many :tags, :through => :resource_tags

我的迁移:

class CreateTags < ActiveRecord::Migration
  def change
    create_table :tags do |t|

      t.string  :name
      t.integer :resource_count, :default => 0

      t.timestamps
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord ruby-on-rails-3.1


    【解决方案1】:

    :counter_cache 选项用于belongs_to 方法

    在资源标签模型中

    belongs_to :tag, :counter_cache => :resource_count
    

    我认为最好将列命名为resources_count(复数)

    【讨论】:

    • 所以我将它移到 :resource 或 :tag 上的 resource_tag 模型中?你能完成你的代码多一点吗?我尝试阅读所有相关内容,但只有 1 行文档
    • 所以现在我在 tag.rb 中有:has_many :resource_tags, :dependent =&gt; :destroy,在 resource_tag.rb 我有 belongs_to :tag, :counter_cache =&gt; :resources_count,在 resource.rb 我有 has_many :resource_tags, :dependent =&gt; :destroy。是对的吗?我的迁移中也有t.integer :resources_count, :default =&gt; 0
    猜你喜欢
    • 2011-07-12
    • 2023-03-07
    • 2011-04-01
    • 1970-01-01
    • 2011-11-19
    • 2014-10-06
    • 2015-11-23
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多