Подтвердить что ты не робот

Counter_cache с has_many: через

Я только что создал поле counter_cache, и контроллер выглядит так.

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

Связь в User.rb

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

Проблема заключается в том, что counter_cache объявляется в атрибуте принадлежностью Like.rb, и я не знаю, как сообщить ему, что для has_many: через объединение.

  belongs_to :user, :counter_cache => :received_likes
4b9b3361

Ответ 1

У вас есть предыдущий

    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

Ответ 2

В соответствии с этот пост (с последнего месяца) и этот пост ( с 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: through = > B

Ответ 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 для тегов или любые ваши ассоциации.