gpt4 book ai didi

ruby-on-rails - 将计数器缓存添加到 rails 中的自连接表

转载 作者:行者123 更新时间:2023-12-05 01:10:15 26 4
gpt4 key购买 nike

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

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

现在我想在 follower 上添加计数器缓存和 followees .我有 followers_countfollowees_count user 中的列 table 。

我试过
belongs_to :follower, :class_name => "User" , :counter_cache => true

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

最佳答案

这是很久以前的事了,但是

用户.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

关于ruby-on-rails - 将计数器缓存添加到 rails 中的自连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15133545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com