用多态反转has_many

Ste*_*win 6 polymorphism ruby-on-rails associations

我有两个模型:用户和项目.这个想法是用户可以关注项目和其他用户.当然,用户和项目是多态"可跟随"类型的一部分.现在,使用用户模型,我想得到三件事:

user.followed_users
user.followed_projects
user.followers
Run Code Online (Sandbox Code Playgroud)

前两个工作正常; 这是我遇到麻烦的第三个问题.这是一种反向查找,其中外键成为下表中的"followable_id"列,但无论我如何建模,我都无法使查询正确运行.

用户模型

has_many :follows, :dependent => :destroy
has_many :followed_projects, :through => :follows, :source => :followable, :source_type => "Project"
has_many :followed_users, :through => :follows, :source => :followable, :source_type => "User"
has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable", :source => :user, :class_name => "User"
Run Code Online (Sandbox Code Playgroud)

关注模型

class Follow < ActiveRecord::Base
  belongs_to :followable, :polymorphic => true
  belongs_to :user
end
Run Code Online (Sandbox Code Playgroud)

我的follow表有:user_id followable_id followable_type

每当我运行查询时,我得到:

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

它应该是"followable_id = 7 AND followable_type ='User",而不是"user_id = 7"

有什么想法吗?

Ste*_*win 6

弄清楚了.看看Michael Hartl做的一个示例项目,并注意到这样做的正确方法是不仅指定一个关系表(在这种情况下是跟随),而且还指定一个反向关系表(我称之为反向关系).

    has_many    :follows,
                        :dependent => :destroy

    has_many    :followed_projects,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "Project"

    has_many    :followed_users,
                        :through => :follows,
                        :source => :followable,
                        :source_type => "User"

    has_many    :reverse_follows,
                        :as => :followable,
                        :foreign_key => :followable_id,
                        :class_name => "Follow"

    has_many    :followers,
                        :through => :reverse_follows,
                        :source => :user
Run Code Online (Sandbox Code Playgroud)

希望这能帮助一些人走出困境!