Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
670 views
in Technique[技术] by (71.8m points)

ruby on rails - Relationship like Twitter followers/followed in 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?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

and the following code in the models

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

and corresponding in the Followings class you write

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...