多态 has_many 自引用
我有很多模型(文章、视频、照片)
现在我正在尝试创建一个 related_to 关联,这样
一篇文章可以有许多与其相关的其他文章、视频和照片。 视频和照片也可以。
这是我尝试过的:
module ActsAsRelatable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def acts_as_relatable
has_many :related_items, :as => :related
has_many :source_items, :as => :source, :class_name => 'RelatedItem'
end
end
end
class relatedItem < ActiveRecord::基础 属于:来源,:多态 => 真的 属于:相关,:多态 => 真的 然后
我已将 acts_as_relatable 添加到我的三个模型(文章、视频、照片)中,并将该模块包含在 ActiveRecord::Base
中尝试在 ./script/console 中时,我让它添加相关项目,并且 ids 正常工作,但是 source_type和 related_type 始终相同(调用 related_items 的对象) 我希望 related_item 是另一个模型名称。
有人有什么想法吗?
I have A number of models (Article, Video, Photo)
Now I am trying to create a related_to association, such that
An article can have many other articles, videos and photos related to it. As can videos and photos.
Heres what I have tried:
module ActsAsRelatable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def acts_as_relatable
has_many :related_items, :as => :related
has_many :source_items, :as => :source, :class_name => 'RelatedItem'
end
end
end
class RelatedItem < ActiveRecord::Base
belongs_to :source, :polymorphic => true
belongs_to :related, :polymorphic => true
end
Then I have added acts_as_relatable to my three models (Article, Video, Photo) and included the module in ActiveRecord::Base
When trying in ./script/console I get it to add the related items and the ids work correctly however the source_type and related_type are always the same (the object that related_items was called from) I want the related_item to be the other model name.
Any ideas anyone?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会使用 has Many Polymorphs 插件,因为它支持双面多态性,你可以做一些事情像这样:
并且不要忘记数据库迁移:
我不知道“相关”是否是一个好名字,但你明白了。 现在,一篇文章、视频和照片可以与另一篇文章、视频或照片相关。
I would use the has many polymorphs plugin since it supports double sided polymorphism you can do something like this:
and don't forget the db migration:
I don't know if "Relating" is a good name, but you get the idea. Now an article, video and photo can be related to another article, video or photo.