像 Twitter 关注者/在 ActiveRecord 中被关注的关系 [英] Relationship like Twitter followers/followed in ActiveRecord

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

问题描述

我试图在我的应用程序中表示用户之间的关系,其中一个用户可以有很多关注者并且可以关注其他用户.我想要像 user.followers() 和 user.followed_by() 这样的东西你能详细告诉我如何使用 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?

谢谢.

推荐答案

你需要两个模型,一个 Person 和一个 Follows

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

以及模型中的以下代码

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

和你写的Follows类对应

and corresponding in the Followings class you write

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

您可以根据自己的喜好使名称更清晰(我特别不喜欢 Followings-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天全站免登陆