带有has_many的counter_cache:through

时间:2011-03-10 07:56:54

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

我刚刚创建了一个counter_cache字段,控制器看起来像这样。

 @users = User.where(:sex => 2).order('received_likes_count')

User.rb中的关联是

 has_many :received_likes, :through => :attachments, :source => :likes, :dependent => :destroy

问题是在Like.rb的belongs_to中声明了counter_cache,我不知道如何告诉它是为了has_many:通过关联。

  belongs_to :user, :counter_cache => :received_likes

3 个答案:

答案 0 :(得分:21)

您之前有

    class Product
      has_and_belongs_to_many :categories
    end

    class Category
      has_and_belongs_to_many :products
    end

和迁移

    class CreateCategoriesProducts < ActiveRecord::Migration
      def change
        create_table :categories_products, id: false do |t|
          t.references :category
          t.references :product
        end

        add_index :categories_products, [:category_id, :product_id]
      end
    end

现在全部改为

    class Product
      has_many :categories_products, dependent: :destroy
      has_many :categories, through: :categories_products
    end

    class Category
      has_many :categories_products, dependent: :destroy
      has_many :products, through: :categories_products
    end

和新的

    class CategoriesProduct < ActiveRecord::Base
      # this model uses table "categories_products" as it is
      # column products_count is in the table "categories"
      belongs_to :category, counter_cache: :products_count
      belongs_to :product
    end

答案 1 :(得分:13)

根据this post(来自上个月)和this post(来自2008年),似乎不可能。但是,后一篇文章确实有解决方法的代码(为方便起见,从该链接复制/粘贴,在第二个链接中转到DEfusion)

class C < ActiveRecord::Base
    belongs_to :B

    after_create :increment_A_counter_cache
    after_destroy :decrement_A_counter_cache

    private

    def increment_A_counter_cache
        A.increment_counter( 'c_count', self.B.A.id )
    end

    def decrement_A_counter_cache
        A.decrement_counter( 'c_count', self.B.A.id )
    end
end

(这是一个方案,其中C属于B,B属于A,A has_many C:通过=&gt; B

答案 2 :(得分:3)

这基本上做同样的事情:

after_save :cache_post_count_on_tags

def cache_post_count_on_tags
  tags.each {|t| tag.update_attribute(:posts_count, t.posts.size)}
end

您需要在标记上添加posts_count列,或者您拥有任何关联。