数据关联 through,到底用什么用?


有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

ruby 模型

Kaede_君 9 years, 8 months ago

你对象的关系是这样的:

Document 1 n Section
Section 1 n Paragraph

Document 和 Section 有一对多的关系,Section 和 Paragraph 有一对多的关系。从而可以得出 Document 有多个 Paragraph,但是他们两没有直接的关系,所以通过(through) Section 关联让他们联系起来。这就是 trough 的作用

被推倒的正太 answered 9 years, 8 months ago

Your Answer