多对多:Rails 中的简单与丰富

Many-to-Many: Simple vs Rich in Rails

我对这两种关系有疑问,因为我想得太多了,自己也很困惑。

所以它们都涉及一个新的 table,它位于您要加入的两个 table 之间。

一个简单的 M2M 从其他两个 table 中获取外键(例如 "blog_posts_categories" table 会得到 blog_post_id 和 category_id 外键)。然后对于关联,blog_post 和类别模型将彼此有 has_and_belongs_to_many 关联,但加入的 table 没有模型。

对于丰富的 M2M,创建了第三个加入的 table。这个 table 从其他两个 table 获取外键,而那两个 table 获取连接的 table 的外键。然后对于 rails 关联,加入的确实得到一个模型,它 belongs_to 其他两个对应的模型。以及加入的 table 模型

的那两个模型 has_many

我是否接近正确?我认为我的问题是我一直将 table 与模型混为一谈,或者至少对于简单的多对多而言,因为我一直期望应该有一个模型与 table 一起使用。

感谢您提供任何指导。

第三个关系 table 是多对多关系的 suitable。你可以这样做:

class BlogPost < ActiveRecord::Base
  has_many :blog_post_categories
  has_many :categories, through: :blog_post_categories
end

class Category < ActiveRecord::Base
  has_many :blog_post_categories
  has_many :blog_posts, through: :blog_post_categories
end

class BlogPostCategory < ActiveRecord::Base
  belongs_to :blog_post
  belongs_to :category
end

第三个模型非常简单,开销基本可以忽略不计。如果您想将更多信息附加到该关系(例如,优先级或时间戳),它也很灵活和广泛。我个人更喜欢为关系使用独立的 table 而不是 blog_posts table.

中的更多列

这是一篇相关的博客post:Why You Don’t Need Has_and_belongs_to_many Relationships

也许您可以在这里解释您正在考虑的权衡?

你对两者的概念理解差不多了。与其将它们视为 简单丰富,我更愿意将它们视为 隐含 与.明确.

以两个模型为例,BookAuthor

对于 has_and_belongs_to_many,Rails 将在您的两个模型之间隐式创建 join table。 IE。 books_authors.

您还可以显式创建连接 table,例如 Authorshipbelongs_to 两者。 (BookAuthor 将有 has_many :authorships。)

在这两种情况下,您的领域模型看起来都一样:

Book (1)--(n) Authorship (n)--(1) Author

现在,这是自以为是的部分。我更喜欢使用显式方法,因为这在概念上更容易掌握,并且可以更轻松地向您的联接添加其他字段 table。例如,假设您想要订购 Authorship,您可以轻松地将 order 列添加到 Authorship 模型并相应地使用它。