Ruby on Rails通过自我引用的跟随/关注者关系

she*_*edd 22 activerecord ruby-on-rails

has_many上有很多帖子和帖子:通过,但我没有找到任何具体涵盖我正在尝试做的事情.

我有一个用户模型和一个友谊模型.用户有许多跟随他们的用户,以及许多关注者.这是通常的Twitter模型.

对于给定用户,我想设置Active Record关系,该关系返回跟随用户并且用户是其关注者的实际用户.

这些是我设置的关系:

class User < ActiveRecord::Base

  has_many :following, :class_name => 'User', :through => :friendships, :foreign_key => 'user_id'

  has_many :followers, :class_name => 'User', :through => :friendships, :foreign_key => 'friend_id'

end

class Friendship < ActiveRecord::Base

  belongs_to :user
  belongs_to :following, :class_name => 'User', :foreign_key => 'friend_id'
  belongs_to :follower, :class_name => 'User', :foreign_key => 'user_id'

end
Run Code Online (Sandbox Code Playgroud)

以下关系有效 - 它生成以下连接:

SELECT `users`.* FROM `users` INNER JOIN `friendships` ON `users`.id = `friendships`.friend_id WHERE ((`friendships`.user_id = 1))
Run Code Online (Sandbox Code Playgroud)

一切都很棒.

但是,追随者关系不起作用.我尝试了很多变化,但大多数似乎都返回与Follow相同的结果集.

我需要按如下方式设置连接以返回正确的结果集.

SELECT `users`.* FROM `users` INNER JOIN `friendships` ON `users`.id = `friendships`.user_id WHERE ((`friendships`.friend_id = 1)); 
Run Code Online (Sandbox Code Playgroud)

我哪里错了?

我可以使用has_many上的finder_sql选项来设置它,但似乎应该有更好的方法.

has_many :followers, :class_name => 'User', :finder_sql => 'SELECT `users`.* FROM `users` INNER JOIN `friendships` ON `users`.id = `friendships`.user_id WHERE ((`friendships`.friend_id = #{ id }))'
Run Code Online (Sandbox Code Playgroud)

谢谢!


我取得了一些进展,最终通过将关系分成两部分来实现关系,如本回复中所示:自我引用has_many:通过自定义:主键问题

# FOLLOWING
has_many :friendships_to, :foreign_key => 'user_id', :class_name => 'Friendship'
has_many :following, :through => :friendships_to, :class_name => 'User'

# FOLLOWERS
has_many :friendships_from, :foreign_key => 'friend_id', :class_name => 'Friendship'
has_many :followers, :through => :friendships_from, :class_name => 'User'
Run Code Online (Sandbox Code Playgroud)

然而,虽然有可能有一个单行版本的关系跟随

has_many :following, :class_name => 'User', :through => :friendships, :foreign_key => 'user_id'
Run Code Online (Sandbox Code Playgroud)

我仍然无法让它为追随者工作.仍然想知道如何做到这一点?

jam*_*s2m 23

您需要确保ActiveRecord知道User#friends以及关注者的源关联,并为ActiveRecord无法从关联名称推断的关系指定class和foreign_key.

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
Run Code Online (Sandbox Code Playgroud)


小智 5

我在学习过程中有点像菜鸟,但这个模型对我来说似乎更干净:

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
Run Code Online (Sandbox Code Playgroud)