【发布时间】:2012-05-29 23:56:44
【问题描述】:
假设我有一个具有“收藏夹”功能的应用程序,用户可以在其中将文档、注释或评论添加到他的收藏夹列表中。
在我看来..
- 用户
has_many收藏 - 收藏
belongs_to一个用户
- 文档
belongs_to收藏夹 - 注意
belongs_to收藏 - 评论
belongs_to收藏
这种关联有什么问题,多态关联有什么帮助?
【问题讨论】:
标签: ruby-on-rails polymorphic-associations
假设我有一个具有“收藏夹”功能的应用程序,用户可以在其中将文档、注释或评论添加到他的收藏夹列表中。
在我看来..
has_many收藏belongs_to一个用户belongs_to收藏夹belongs_to 收藏belongs_to收藏这种关联有什么问题,多态关联有什么帮助?
【问题讨论】:
标签: ruby-on-rails polymorphic-associations
因为你最喜欢的实例将不知道它喜欢什么:)
它知道它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
(只需正确设置您的数据库)此设计是此类收藏用例的标准。
【讨论】: