问题描述
有3个模型,document, section, paragraph。
d = Document.new
直接执行 d.sections.to_sql 或者 d.paragraphs.to_sql或者是 d.sections.to_sql会报错,因为没有关联。
问题1:
现在把他们关联了,(我测试后发现添加了has_many后显示的d.sections.to_sql或者是其他模型.to_sql在添加through关系前和后打印都是一样的),那么我就不知道这个through到底有什么用?不是多余的吗?
问题2:
添加了如下关系后,d.section.to_sql报错,为什么会出现这样的错误?
irb(main):008:0> d.sectionsSystemStackError: stack level too deepclass Document < ActiveRecord::Base has_many :paragraphs, through: :sections has_many :sections endclass Paragraph < ActiveRecord::Base belongs_to :sectionendclass Section < ActiveRecord::Base belongs_to :document has_many :paragraphsend
问题解答
回答1:你对象的关系是这样的:
Document 1 n SectionSection 1 n Paragraph
Document 和 Section 有一对多的关系,Section 和 Paragraph 有一对多的关系。从而可以得出 Document 有多个 Paragraph,但是他们两没有直接的关系,所以通过(through) Section 关联让他们联系起来。这就是 trough 的作用