且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

像Twitter的追随者/遵循ActiveRecord的关系

更新时间:2023-11-19 14:45:40

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

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.