【问题标题】:What do polymorphic associations solve?多态关联解决了什么问题?
【发布时间】:2012-05-29 23:56:44
【问题描述】:

假设我有一个具有“收藏夹”功能的应用程序,用户可以在其中将文档、注释或评论添加到他的收藏夹列表中。

在我看来..

  • 用户has_many收藏
  • 收藏belongs_to一个用户

  • 文档belongs_to收藏夹
  • 注意belongs_to 收藏
  • 评论belongs_to收藏

这种关联有什么问题,多态关联有什么帮助?

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案1】:

    因为你最喜欢的实例将不知道它喜欢什么:) 它知道它has_one :note,但也有:comment,或者?但肯定不是两者兼而有之。

    相反的多态关联会有所帮助,因为它将表示 Favorite 对象属于多态 :favorited 对象,因为它可以是任何类,其名称将存储在 @ 987654325@ string db 列,因此您最喜欢的对象会知道它偏爱注释或文档或评论。

    一些代码

    class Note
      has_many :favorites, :as => :favorited
      has_many :fans, :through => :favorites, :source => :user
    end
    
    class Discussion
      has_many :favorites, :as => :favorited
      has_many :fans, :through => :favorites, :source => :user
    end
    
    class Comment
      has_many :favorites, :as => :favorited
      has_many :fans, :through => :favorites, :source => :user
    end
    
    class Favorite
      belongs_to :user
      belongs_to :favorited, :polymorphic => true # note direction of polymorphy
    end
    
    class User
      has_many :favorites
      has_many :favorite_notes, :through =>  :favorites, :source => favorited, :source_type => "Note"
      has_many :favorite_comments, :through =>  :favorites, :source => favorited, :source_type => "Comment"
      has_many :favorite_discussions, :through =>  :favorites, :source => favorited, :source_type => "Discussion"
    
    end
    

    (只需正确设置您的数据库)此设计是此类收藏用例的标准。

    【讨论】:

    • 我不确定我是否遵循。多态关联解决了什么问题?如果可以的话,请在我的例子中描述你的答案(除非我的例子不相关,在这种情况下,什么例子有关系?)。谢谢。
    • 我想我确实在您的示例的上下文中进行了解释。我添加了一些代码,希望对您有所帮助。
    • 正如我所说,我不确定我是否遵循您的回答是否适合我的问题。再说一遍,多态关联解决了什么问题?
    • 试着用你在“我的脑海里”下建议的关系来编码,然后你就会明白了。提示:给我方法调用以获得用户最喜欢的讨论。
    • 好的,如果我这样做了:用户 has_many 收藏夹,注意 has_many 收藏夹。另一方面:Favorite belongs_to User,Favorite belongs_to Note。现在每个收藏夹将引用一个用户和一个注释(或其他模型)。然后我可以找到一个 User.first.favorites.each {|f| f.note}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2017-08-26
    • 2010-09-21
    • 1970-01-01
    • 2014-04-26
    • 2011-04-06
    • 2019-12-29
    相关资源
    最近更新 更多