rails many to many self join

后端 未结 4 2054

could some one point me to the right direction:

I try to build a model for rails that build up the following:

ClassA -id

ClassA has a relation to

4条回答
  •  一整个雨季
    2020-11-30 04:59

    I'd use something like

    class Person < ActiveRecord::Base
       has_many :friendships, :foreign_key => "person_id", 
          :class_name => "Friendship"
    
       has_many :friends, :through => :friendships
    end
    
    class Friendship < ActiveRecord::Base
       belongs_to :person, :foreign_key => "person_id", :class_name => "Person"
       belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person"  
    end
    

    And the tables would be like

    people: id; name; whatever-you-need    
    friendships: id; person_id; friend_id
    

提交回复
热议问题