4

我正在尝试在自联接关联的 aa 列上添加计数器缓存。我有两个模型用户和追随者。用户有来自用户表本身的关注者和关注者。

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

现在我想在followerand上添加计数器缓存followees。我在表中有followers_countfollowees_countuser

我试过了

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

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

4

2 回答 2

3

很久很久以前,但是

用户.rb

class User < ActiveRecord::Base
  has_many :followings_as_follower, class_name: 'Following', foreign_key: 'follower_id', dependent: :destroy
  has_many :followings_as_followee, class_name: 'Following', 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

关注.rb

class Following < ActiveRecord::Base
  belongs_to :follower, class_name: 'User', counter_cache: :followees_count
  belongs_to :followee, class_name: 'User', counter_cache: :followers_count
  validates :follower, presence: true
  validates :followee, presence: true
  validates :followee, uniqueness: { scope: [:follower, :followee] }
end
于 2015-03-11T00:52:08.387 回答
2

尝试这个,

belongs_to :follower, foreign_key: 'the_id_of_foreign_key', class_name: 'User', counter_cache: :followers_count

您可以使用column_name代替truein counter_cache

于 2013-02-28T11:01:25.733 回答