How to model a mutual friendship in Rails

后端 未结 3 541
小蘑菇
小蘑菇 2021-01-03 09:02

I know this question has been asked before on Stack Overflow, but the answers aren\'t doing it for me in ways I can explain. My general approach was inspired by this tutoria

3条回答
  •  耶瑟儿~
    2021-01-03 09:47

    Maybe this:

    friendship.rb
    belongs_to :friend_one, :foreign_key => :user_id
    belongs_to :friend_two, :foreign_key => :friendship_id
    

    and

    user.rb
    
    has_many :friendship_ones, :class_name => 'Friendship', :foreign_key => :friendship_id
    has_many :friend_ones, through: :friendship_ones
    has_many :friendship_twos, :class_name => 'Friendship', :foreign_key => :user_id
    has_many :friend_twos, through: :friendship_twos
    
    
    def friends
      friend_ones + friend_twos
    end
    

    You get two queries to find the friends, but it is a simple data model and you you do just call @user.friends to find the instances.

    It would be amenable to eager loading, if you load the two friend_ones and friend_twos associations.

提交回复
热议问题