将计数器缓存添加到rails中的自联接表

时间:2013-02-28 10:49:05

标签: ruby-on-rails self-join counter-cache

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

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

现在我想在followerfollowees添加计数器缓存。我在followers_count表格中有followees_countuser列。

我试过

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

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

2 个答案:

答案 0 :(得分:3)

很久以前,但是

<强> 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, 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

<强> Following.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

答案 1 :(得分:2)

试试这个,

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

您可以在column_name中使用true代替counter_cache