像Twitter的追随者/遵循ActiveRecord的关系 [英] Relationship like Twitter followers/followed in ActiveRecord

查看:137
本文介绍了像Twitter的追随者/遵循ActiveRecord的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重新present在我的应用程序的用户之间的关系,其中一个用户都可以有众多的追随者,并可以按照其他用户。 我想有像user.followers()和user.followed_by() 你能告诉我详细介绍了如何重新present此使用的ActiveRecord?

I'm trying to represent a relationship between users in my application where a user can have many followers and can follow other users. I would like to have something like user.followers() and user.followed_by() Could you please tell me in details how to represent this using ActiveRecord?

感谢。

推荐答案

您需要两个模型,一个人与追随中

You need two models, a Person and a Followings

rails generate model Person name:string
rails generate model Followings person_id:integer follower_id:integer blocked:boolean

和以下code在模型

class Person < ActiveRecord::Base
  has_many :followers, :class_name => 'Followings', :foreign_key => 'person_id'
  has_many :following, :class_name => 'Followings', :foreign_key => 'follower_id' 
end

和相应的追随中类你写

class Followings < ActiveRecord::Base
  belongs_to :person
  belongs_to :follower, :class_name => 'Person'
end

您可以根据自己的喜好更清楚的名称(我特别不喜欢以下内容 -name),但这应该让你开始。

You could make the names clearer to your liking (i especially don't like the Followings-name), but this should get you started.

这篇关于像Twitter的追随者/遵循ActiveRecord的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆