Rails 3 中的自引用模型 [英] Self-referencing models in Rails 3

查看:15
本文介绍了Rails 3 中的自引用模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实体模型,我想显示实体之间的连接.即,实体 1 连接到实体 2.

I have an Entity model and I want to display connections between the Entities. ie, Entity 1 is connected to Entity 2.

我现在的想法是在两者之间创建一个名为 Connection 的连接模型,并让它像传统的 rails 连接表一样工作.除了列是entity_one_id和entity_two_id,然后在Entity和Connection之间建立多对多的关系.

My thinking, right now, is to create a join model between the two called Connection and have it work like a traditional rails join table. Except have the columns be entity_one_id and entity_two_id, then establish a many-to-many relationship between Entity and Connection.

这似乎是一种非常不优雅的方法.我想知道是否有人有更好的想法?也许是我没有看到的更轨式的东西?

This seems like a really not-elegant way to do this. I was wondering if anyone had any better ideas? Maybe something more rails-esque that I'm just not seeing?

推荐答案

这是最常用的方法.如果一个实体只连接到另一个模型,您可以使用链表、树状结构.

That's the most-common way to do it. If an entity is only ever connected to one other model, you could use a linked-list, tree-like structure.

查看 Ryan Bates 关于自联接模型的 Railscast.它处理类似社交网络的系统,但它仍然具有您需要的原则并提供了一个很好的起点

Check out Ryan Bates' Railscast on self-joining models. It deals with a social-network-like system, but it still has principles you'll need and provides a great starting point

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

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