有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.sections
SystemStackError: stack level too deep
class Document < ActiveRecord::Base
has_many :paragraphs, through: :sections
has_many :sections
end
class Paragraph < ActiveRecord::Base
belongs_to :section
end
class Section < ActiveRecord::Base
belongs_to :document
has_many :paragraphs
end
The relationship between your partner is like this:
Document 1 n Section
Section 1 n Paragraph
Document and Section have a one-to-many relationship, and Section and Paragraph have a one-to-many relationship. It can be concluded that Document has multiple Paragraphs, but they are not directly related, so they are connected through (through) Section association. This is what trough does