我有两个型号用户和以下.用户拥有关注者和关注者,他们来自用户表本身.
User.rb has_many :followings has_many :followers,:through => :followings has_many :followees,:through => :followingsFollowing.rbclass 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 endend
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总结
以上是内存溢出为你收集整理的ruby-on-rails – 在rails中为自联接表添加计数器缓存全部内容,希望文章能够帮你解决ruby-on-rails – 在rails中为自联接表添加计数器缓存所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)