【问题标题】:Reverse has_many with polymorphism具有多态性的反向 has_many
【发布时间】:2012-05-14 11:49:03
【问题描述】:

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

user.followed_users
user.followed_projects
user.followers

前两个工作正常;这是我遇到麻烦的第三个。这是一种反向查找,其中外键成为下表中的“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"

跟随模型

class Follow < ActiveRecord::Base
  belongs_to :followable, :polymorphic => true
  belongs_to :user
end

我的下表有: 用户身份 followable_id followable_type

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

SELECT `users`.* FROM `users` INNER JOIN `follows` ON `users`.`id` = `follows`.`user_id` WHERE `follows`.`user_id` = 7

应该是“followable_id = 7 AND followable_type = 'User”,而不是“user_id = 7”

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails associations polymorphism


    【解决方案1】:

    想通了。看了一下sample project Michael Hartl made,发现正确的做法是不仅要指定一个关系表(在这种情况下如下),还要指定一个反向关系表(我称之为反向关系)。

        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
    

    希望这对一些人有所帮助!

    【讨论】:

      【解决方案2】:

      我认为您需要明确地拼出外键。你有:

      :foreign_key => "followable"
      

      你需要:

      :foreign_key => "followable_id"
      

      完整代码:

      has_many :followers, :through => :follows, :as => :followable, :foreign_key => "followable_id", :source => :user, :class_name => "User"
      

      【讨论】:

      • 不,如果你不包含它,Rails 会自动附加“_id”。我只是试了一下,还是没有运气
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      相关资源
      最近更新 更多