Rails 多态多对多关联 [英] Rails polymorphic many to many association

查看:46
本文介绍了Rails 多态多对多关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试设置一种通用的相关对象网络.假设我有 4 个模型.

I'm trying setup a generic sort of web of related objects. Let say I have 4 models.

  • 预订
  • 电影
  • 标签
  • 类别

我希望能够做到:

book = Book.find(1)
book.relations << Tag.find(2)
book.relations << Category.find(3)
book.relations #=> [Tag#2, Category#3]

movie = Movie.find(4)
movie.relations << book
movie.relations << Tag.find(5)
movie.relations #=> [Book#1, Tag#5]

基本上我希望能够获取任何模型类(或我允许的模型类)的任何 2 个对象并声明它们是相关的.

Basically I want to be able to take any 2 objects of any model class (or model class that I allow) and declare that they are related.

显然我不想创建一大堆连接表.这似乎不是一个有很多通过关联,也不是一个多态关联.

Obviously I don't want to create a huge mess of join tables. This seems like it's not quite a has many through association, and not quite a polymorphic association.

这是 Rails 可以通过它的关联声明支持的东西,还是我应该在这里滚动我自己的逻辑?

Is this something that Rails can support via it's association declarations or should I be rolling my own logic here?

推荐答案

我想出了一些解决方案.然而,我不确定它是最好的.看来你不能通过多态 has_many.

I have come up with a bit of solution. I'm not sure it's the best however. It seems you cannot have a polymorphic has_many through.

所以,我假装了一下.但这意味着放弃我非常喜欢的关联代理魔法,这让我很伤心.在基本状态下,它是如何工作的.

So, I fake it a bit. But it means giving up the association proxy magic that I love so much, and that makes me sad. In a basic state, here is how it works.

book = Book.find(1)
book.add_related(Tag.find(2))
book.add_related(Category.find(3))
book.related        #=> [Tag#2, Category#3]
book.related(:tags) #=> [Tag#2]

我将它封装在一个可重用的模块中,该模块可以通过一个 has_relations 类方法添加到任何模型类中.

I wrapped it up in a reusable module, that can be added to any model class with a single has_relations class method.

http://gist.github.com/123966

我真的希望我不必完全重新实现关联代理来处理这个问题.

I really hope I don;t have to completely re-implement the association proxy to work with this though.

这篇关于Rails 多态多对多关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆