Relationship like Twitter followers/followed in ActiveRecord

前端 未结 2 960
终归单人心
终归单人心 2020-12-04 13:53

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

相关标签:
2条回答
  • 2020-12-04 14:10

    The twitter follower model differs from the friendship model in that you do not need permission from the person to follow them. Here I set up a lazy loading where the relationship is not fully defined in the person object.

    /app/models/person.rb

      def followers
        Followership.where(:leader_id=>self.id).not_blocked
      end
    
      def following
        Followership.where(:follower_id=>:self.id).not_blocked
      end
      has_many :followers, :class_name=>'Followership'
      has_many :followed_by, :class_name=>'Followership'
    

    /app/models/followership.rb

      belongs_to :leader, :class_name=>'Person'
      belongs_to :follower, :class_name=>'Person'
    
      #leader_id integer
      #follower_id integer
      #blocked boolean
    
      scope :not_blocked, :conditions => ['blocked = ?', false] 
    
    0 讨论(0)
  • 2020-12-04 14:22

    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.

    0 讨论(0)
提交回复
热议问题