Rails:多对多态关系 [英] Rails: Many to many polymorphic relationships
问题描述
查看评论以获取更新.
我一直在努力获得一个清晰而直接的答案,我希望这次我能得到! :D 我当然仍然需要对Rails进行很多学习,但是我确实了解我所面临的问题,并且非常感谢其他帮助.
I've been struggling to get a clear and straight-forward answer on this one, I'm hoping this time I'll get it! :D I definitely have a lot to learn still with Rails, however I do understand the problem I'm facing and would really appreciate additional help.
- 我有一个名为任务"的模型.
- 我有一个称为目标"的抽象模型.
- 我想将Target的子类的多个实例与Task相关联.
- 我没有使用单表继承.
- 我想查询多态关系以返回Target子类的混合结果集.
- 我想查询Target子类的各个实例,以获得与它们有关系的任务.
因此,我认为Task和Targets的子类之间的多态性是多对多的关系. 更详细地讲,我将能够在控制台(当然还有其他地方)中执行以下操作:
So, I figure a polymorphic many to many relationship between Tasks and subclasses of Targets is in order. In more detail, I will be able to do things like this in the console (and of course elsewhere):
task = Task.find(1)
task.targets
[...array of all the subclasses of Target here...]
但是!假设存在目标"子类的模型商店",软件",办公室",车辆",那么最好也沿另一个方向遍历关系:
But! Assuming models "Store", "Software", "Office", "Vehicle", which are all subclasses of "Target" exist, it would be nice to also traverse the relationship in the other direction:
store = Store.find(1)
store.tasks
[...array of all the Tasks this Store is related to...]
software = Software.find(18)
software.tasks
[...array of all the Tasks this Software is related to...]
由多态关系暗示的数据库表似乎能够执行这种遍历,但是在尝试找到对我不利于多态关系精神的答案的过程中,我看到了一些重复出现的主题:
The database tables implied by polymorphic relationships appears to be capable of doing this traversal, but I see some recurring themes in trying to find an answer which to me defeat the spirit of polymorphic relationships:
- 仍然以我的示例为例,人们似乎想定义任务中的商店,软件,办公室,车辆,我们可以立即知道这不是多态关系,因为它仅返回一种类型的模型.
- 类似于最后一点,人们仍然想以一种形状或形式定义Task中的商店,软件,办公室和车辆.这里重要的一点是,该关系对子类是盲目的.我的多态最初将仅作为目标与之交互,而不作为其各自的子类类型与之交互.出于多态关系的目的,再次在Task中定义每个子类开始变得困难.
- 我看到联接表的模型可能是有序的,对我来说似乎有些正确,除了它增加了一些我认为Rails愿意消除的复杂性.我对此没有经验.
在Rails功能或集体社区知识方面似乎都是一个小漏洞.因此,希望stackoverflow可以编入我的搜索答案!
It seems to be a small hole in either rails functionality or the collective community knowledge. So hopefully stackoverflow can chronicle my search for the answer!
感谢所有提供帮助的人!
Thanks to everyone who help!
推荐答案
您可以将多态与has_many :through
结合使用以获得灵活的映射:
You can combine polymorphism and has_many :through
to get a flexible mapping:
class Assignment < ActiveRecord::Base
belongs_to :task
belongs_to :target, :polymorphic => true
end
class Task < ActiveRecord::Base
has_many :targets, :through => :assignment
end
class Store < ActiveRecord::Base
has_many :tasks, :through => :assignment, :as => :target
end
class Vehicle < ActiveRecord::Base
has_many :tasks, :through => :assignment, :as => :target
end
...等等.
这篇关于Rails:多对多态关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!