如何在Rails中创建关注者和关注者?

时间:2016-07-23 14:29:50

标签: ruby-on-rails ruby relationship

我非常关注Ruby on Rails关系,我非常感谢你的帮助。

拥有模型用户

class User < ActiveRecord::Base
  has_many :followers, :through => :follows, foreign_key: "followee_id"
  has_many :followees, :through => :follows, foreign_key: "follower_id"
end

和模型关注

class Follow < ActiveRecord::Base
  belongs_to :followee, class_name: "User"
  belongs_to :follower, class_name: "User"
end

但是如果想要创建新的关注者:

user.followers << User.first

结果是SystemStackError

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你必须尝试这样的事情:

class User < ActiveRecord::Base
      has_many :follower_follows, foreign_key: :followee_id, class_name: "Follow" 
      has_many :followers, through: :follower_follows, source: :follower
      has_many :followee_follows, foreign_key: :follower_id, class_name: "Follow"
      has_many :followees, through: :followee_follows, source: :followee
    end

这里的follower_follows和followee_follows是连接表和来源::关注者与关注模型和来源中的belongs_to:关注者标识匹配:: followee与关注模型中的belongs_to:followee标识匹配

我认为这适用于您的情况