“继承的” Rails 中的数据

发布于 2024-10-30 19:35:14 字数 477 浏览 2 评论 0原文

我有一个数据模型,我想在 Rails 中描述它。有许多 Entity,每个 has_many :blob,每个 Blob belongs_to 一个 Entity.此外,每个实体可以属于实体。它应该继承父级的所有 Blob。 Rails 有什么好的建模方法吗?换句话说,有没有办法做这样的事情:

# Beware, wrong code
class Entity < ActiveRecord::Base
  has_many :blobs
  has_many :blobs, :through => :parent, :source => :blobs
end

或者也许有不同的想法来做到这一点?

I have a datamodel, which I want to describe in Rails. There are many Entity, each one has_many :blobs, and each Blob belongs_to one Entity. Additionally, each Entity may belong_to a parent Entity. It should inherit all of the parent's Blobs. Is there any nice way of modeling this in Rails? Stated differently, is there a way of doing something like this:

# Beware, wrong code
class Entity < ActiveRecord::Base
  has_many :blobs
  has_many :blobs, :through => :parent, :source => :blobs
end

Or maybe a different idea on how to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

木有鱼丸 2024-11-06 19:35:14

与此非常相似的东西应该有效:

class Entity
  belongs_to :parent, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :children, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :direct_blobs, :class_name => 'Blob'
  has_many :inherited_blobs, :class_name => 'Blob', :through => :parent, :source => :direct_blobs

  def blobs
    direct_blobs + inherited_blobs
  end
end

Something very similar to this should work:

class Entity
  belongs_to :parent, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :children, :class_name => 'Entity', :foreign_key => 'parent_id'
  has_many :direct_blobs, :class_name => 'Blob'
  has_many :inherited_blobs, :class_name => 'Blob', :through => :parent, :source => :direct_blobs

  def blobs
    direct_blobs + inherited_blobs
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文