数据库 twitter 风格好友系统中黑名单功能如何设计

nowherekai · 2014年12月11日 · 最后由 pynix 回复于 2017年04月22日 · 3791 次阅读

rails 教程中有一章https://www.railstutorial.org/book/following_users是讲如何实现类似 twitter 风格的可以 follow,unfllow 的好友系统的,数据库设计如下: 一个 users 表

id               | integer              
name         | character varying(255)

relationships 表

id                | integer           
follower_id  | integer
followed_id | integer

model 如下

class User < ActiveRecord::Base

  has_many :active_relationships, class_name: "Relationship", foreign_key: "follower_id", dependent: :destroy
  has_many :following, through: :active_relationships, source: "followed"

  has_many :passive_relationships, class_name: "Relationship", foreign_key: "followed_id", dependent: :destroy
  has_many :followers, through: :passive_relationships, source: :follower

  def follow(other_user)
    active_relationships.create(followed_id: other_user.id)
  end

  def unfollow(other_user)
    active_relationships.find_by(followed_id: other_user.id).destroy
  end

  def following?(other_user)
    following.include? other_user
  end
end

class Relationship < ActiveRecord::Base
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
end

在此基础上加上黑名单功能,我想到的方案是 在 relationships 表中加入一个状态(status)字段,不过这样做之后逻辑变的复杂很多,还有其他设计方案吗?

新增一个黑名单表。

恩 再加个表应该更好处理,我两种都试试吧

分开逻辑比较清晰,放在一起以后重构麻烦。Enjoy

新建一个 model

需要 登录 后方可回复, 如果你还没有账号请 注册新账号