mongoid 自我与自我的关系?

发布于 2024-12-05 23:49:52 字数 380 浏览 1 评论 0原文

大家好,我有一个像下面这样的爬虫模型类:

class Link
  include Mongoid::Document
  include Mongoid::Timestamps
  field :url, type: String
  field :links, type: String
  index :url
  has_many :pages
end

其中一个链接重复一个 URL 并且它们有许多入站/出站连接,我想让它工作,所以:

a_link.links  # => gives a list of outbound link objects.

你会如何使用 mongoid 来做到这一点?

Hi guys I have a class like below for a crawler model:

class Link
  include Mongoid::Document
  include Mongoid::Timestamps
  field :url, type: String
  field :links, type: String
  index :url
  has_many :pages
end

where a link repent a URL and they have many inbound/outbound connections, I would like to have it working, so:

a_link.links  # => gives a list of outbound link objects.

How would you do it with mongoid?

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

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

发布评论

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

评论(2

瀟灑尐姊 2024-12-12 23:49:52

您可以在关系的每一方使用 has_and_belongs_to_many 来设置多对多关联。

class Link
  include Mongoid::Document
  has_and_belongs_to_many :links, :class_name => 'Link', :inverse_of => :inbound_links
  has_and_belongs_to_many :inbound_links, :class_name => 'Link', :inverse_of => :links
end

由于在这种情况下关联是往返于同一个类,因此您需要为 mongoid 提供有关 class_name 和 inverse_of 的一些帮助,因为它无法从关联名称中推断出这一点。

You can set up a many-many association using has_and_belongs_to_many on each side of the relationship.

class Link
  include Mongoid::Document
  has_and_belongs_to_many :links, :class_name => 'Link', :inverse_of => :inbound_links
  has_and_belongs_to_many :inbound_links, :class_name => 'Link', :inverse_of => :links
end

As the association is to and from the same class in this case you need to give mongoid a little help with the class_name and inverse_of because it can't infer this from the association name.

烟酉 2024-12-12 23:49:52

使用许多关联来归档此文件的更干净的方法

class Link
  include Mongoid::Document
  has_and_belongs_to_many :links, class_name: 'Link', inverse_of: :links
end

a bit cleaner way to archive this using many-many associations

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