Rails 3 中的自引用模型
我有一个实体模型,我想显示实体之间的连接。即,实体 1 连接到实体 2。
我现在的想法是在两者之间创建一个称为 Connection 的连接模型,并使其像传统的 Rails 连接表一样工作。除了列为entity_one_id和entity_two_id之外,然后在Entity和Connection之间建立多对多关系。
这似乎是一种非常不优雅的方法。我想知道是否有人有更好的想法?也许是我没有看到的更铁轨风格的东西?
I have an Entity model and I want to display connections between the Entities. ie, Entity 1 is connected to Entity 2.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是最常见的方法。如果一个实体仅连接到一个其他模型,则可以使用链表、树状结构。
查看 Ryan Bates 的关于自连接模型的 Railscast。它涉及类似社交网络的系统,但它仍然具有您需要的原则并提供了一个很好的起点
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.
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
你可以使用这个实现:
You could use this implementation: