Active Record,如何正确建立N-N关系?

Active Record, how to make N-N relationship properly?

我在 tables Notebook 和 Part 之间有 N-N 关系。一个笔记本有很多部分,一个部分可以出现在许多笔记本中。下面是架构示例:

在其他方法中,正如 AJFaraday 在评论中所建议的那样,我将有一个单独的连接 table notebook-parts,其作用是识别它是否是 gpu、处理器等:

如何使用方法 2 在 Rails 中调用 notebook.processor, notebook.gpu 等?而且我还需要一些空的部分,因为有些笔记本没有专用的 gpu,或者可能只有 ssd 而没有 hd 等?

模型的关系应该如何?

只需为连接创建一个模型 table 并在两个模型中引用它。

# models/notebook_part.rb
class NotebookPart
  belongs_to :notebook
  belongs_to :part
end

# models/part.rb
class Part
  has_many :notebook_parts
  has_many :notebooks, though: :notebook_parts
end

# models/notebook.rb
class Notebook
  has_many :notebook_parts
  has_many :parts, though: :notebook_parts
end

然后在您的笔记本模型中,您可以创建基于零件角色的方法,例如:

# models/notebook.rb
def processors
  parts.where(part_role: :processor)
end

然后为您认为必要的任何其他角色创建该列表,或者考虑一些元编程循环来为您创建这些列表。