Bidirectional self referential associations

前端 未结 1 1454
礼貌的吻别
礼貌的吻别 2021-01-03 05:54

Taking Ryan Bates\' asciicast as an example: http://asciicasts.com/episodes/163-self-referential-association

He ends with two associations of User

  • :fri
相关标签:
1条回答
  • 2021-01-03 06:30

    see if this works for you?

    class User < ActiveRecord::Base
      has_many :friendships, :foreign_key => "person_id", :class_name => "Friendship"
      has_many :friends, :through => :friendships
    
      def befriend(user)
        # TODO: put in check that association does not exist
        self.friends << user
        user.friends << self
      end
    end
    
    class Friendship < ActiveRecord::Base
      belongs_to :person, :foreign_key => "person_id", :class_name => "User"
      belongs_to :friend, :foreign_key => "friend_id", :class_name => "User"  
    end
    
    # Usage
    jack = User.find_by_first_name("Jack")
    jill = User.find_by_first_name("Jill")
    
    jack.befriend(jill)
    
    jack.friends.each do |friend|
      puts friend.first_name
    end
    # => Jill
    
    jill.friends.each do |friend|
      puts friend.first_name
    end
    # => Jack
    

    this is given a database table schema of

    users
      - id
      - first_name
      - etc...
    
    friendships
      - id
      - person_id
      - friend_id
    
    0 讨论(0)
提交回复
热议问题