Rails 3 中的自引用模型

发布于 2024-10-12 18:47:30 字数 231 浏览 8 评论 0原文

我有一个实体模型,我想显示实体之间的连接。即,实体 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

秋风の叶未落 2024-10-19 18:47:30

这是最常见的方法。如果一个实体仅连接到一个其他模型,则可以使用链表、树状结构。

查看 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

说谎友 2024-10-19 18:47:30

你可以使用这个实现:

class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
  has_many :friendships, :dependent => :destroy
end


class Friendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend, :class_name => "User"
end

You could use this implementation:

class User < ActiveRecord::Base
  has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
  has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
  has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
  has_many :friendships, :dependent => :destroy
end


class Friendship < ActiveRecord::Base
   belongs_to :user
   belongs_to :friend, :class_name => "User"
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文