Ruby on Rails has_many through self-referential following/follower relationships

后端 未结 2 2061
天命终不由人
天命终不由人 2020-12-28 15:49

There are a number of posts and threads on has_many :through, but I haven\'t found any that cover specifically what I\'m trying to do.

I have a User model and a Fri

相关标签:
2条回答
  • 2020-12-28 16:22

    I'm kind of a noob in a learning process, but this models seem cleaner to me:

    class User < ActiveRecord::Base
      has_many :followings
      has_many :followers, through: :followings
    end
    
    class Following < ActiveRecord::Base
      belongs_to :user
      belongs_to :follower, class_name: 'User'
    end
    
    • Source Treehouse : https://www.youtube.com/watch?v=jSUWu50XK48
    0 讨论(0)
  • 2020-12-28 16:36

    You need to make sure ActiveRecord knows what the source association for the User#friends and likewise the followers and specify the class and foreign_key for the relationships that ActiveRecord can't extrapolate from the association names.

    class Following < ActiveRecord::Base
    
      belongs_to :user
      belongs_to :followed, :class_name => 'User'
    
    end
    
    class User < ActiveRecord::Base
    
      has_many :followings
      has_many :friends, :through => :followings, :source => 'followed'
    
      has_many :followeds, :class_name => 'Following', :foreign_key => 'followed_id'
      has_many :followers, :through => :followeds, :source => :user
    
    end
    
    0 讨论(0)
提交回复
热议问题