the best way to implement a friendship model in rails

后端 未结 1 1914
無奈伤痛
無奈伤痛 2021-02-06 15:07

I want to implement a user\'s friends system in my app so i found the rails space solution very nice, the idea there is to create two lines in the Friends

相关标签:
1条回答
  • 2021-02-06 15:33

    I would prefer the version that needs two connections between the friends, one for each direction. The reason is the same you mentioned: It allows more Rails-like queries on a user's friends.

    Furthermore I think it would be clearer to have different tables for friendship request (one direction) and existing friendships (two directions)

    Since you have a friendship model in the middle, I suggest to use the magic of callbacks. If you define some callbacks, it must be possible that you only have to take cake for one side of the connection, the callback should should be able to create (or delete) the matching complement.

    # in friendship_requests
    after_save :created_friendship
    
    def accept
      update_attributes(:status  => 'accepted')
    end
    
    private
      def created_friendship
        sender.friends << receiver  if status_changed? && status == 'accepted'
      end
    
    
    # in user.rb
    has_and_belongs_to_many :friends, after_add:    :create_complement_friendship,
                                      after_remove: :remove_complement_friendship
    
    private
      def create_complement_friendship(friend)
        friend.friends << self  unless friend.friends.include?(self)
      end
    
      def remove_complement_friendship(friend)
        friend.friends.delete(self)
      end
    

    This is just a first idea, for sure some validators and callbacks are missing...

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