【问题标题】:Rails polymorphic associations, two assoc types in one classRails 多态关联,一类中有两种关联类型
【发布时间】:2009-12-29 19:45:13
【问题描述】:

考虑一个类:

class Link < ActiveRecord::Base

  has_many :link_votes, :as => :vote_subject, :class_name => 'Vote'
  has_many :spam_votes, :as => :vote_subject, :class_name => 'Vote'

end

问题是,当我用@link.link_votes &lt;&lt; Vote.new 添加新投票时,vote_subject_type'Link',而我希望它可以是'link_votes' 或类似的东西。这是 AR 限制还是有办法解决这个问题?

我实际上找到了一个相关的答案,但我不太确定它说的是什么:Polymorphic Association with multiple associations on the same model

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations model-associations


    【解决方案1】:

    听起来您想使用单表继承 - 这将允许您拥有两种不同类型的投票。这将在投票表中添加一个“类型”列,然后您将作为 LinkVote 或 SpamVote 访问该列

    class SpamVote << Vote
      ...
    end
    

    沿着这些思路。

    class Link < ActiveRecord::Base
    
      has_many :link_votes, :as => :vote_subject
      has_many :spam_votes, :as => :vote_subject
    
    end
    

    在投票表中,您会看到如下列:

    id, type, vote_subject_type, vote_subject_id, etc.
    

    对 STI 进行更多研究,我打赌你会找到答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多