ruby-on-rails – 在rails中为自联接表添加计数器缓存

我试图在自联接关联中的列上添加计数器缓存.
我有两个型号用户和以下.用户拥有关注者和关注者,他们来自用户表本身.

User.rb

  has_many :followings
  has_many :followers,:through => :followings
  has_many :followees,:through => :followings

Following.rb

class Following < ActiveRecord::Base
  attr_accessible :followee_id,:follower_id
  belongs_to :follower,:class_name => "User" 
  belongs_to :followee,:class_name => "User"
end

现在我想在追随者和追随者上添加计数器缓存.我在用户表中有followers_count和followees_count列.

我试过了

belongs_to :follower,:class_name => "User",:counter_cache => true

但是这不会返回用户表中的任何数据.
任何帮助,将不胜感激.

解决方法

很久以前,但是

User.rb

class User < ActiveRecord::Base
  has_many :followings_as_follower,class_name: 'Following',foreign_key: 'follower_id',dependent: :destroy
  has_many :followings_as_followee,foreign_key: 'followee_id',dependent: :destroy
  has_many :followers,through: :followings_as_followee,source: :follower
  has_many :followees,through: :followings_as_follower,source: :followee

  def follow?(user)
    followees.reload.include? user
  end

  def follow(user)
    return if follow?(user)
    followings_as_follower.create(followee: user)
  end

  def unfollow(user)
    return unless follow?(user)
    followings_as_follower.where(followee: user).first.destroy
  end
end

Following.rb

class Following < ActiveRecord::Base
  belongs_to :follower,class_name: 'User',counter_cache: :followees_count
  belongs_to :followee,counter_cache: :followers_count
  validates :follower,presence: true
  validates :followee,uniqueness: { scope: [:follower,:followee] }
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...