ホームページ  >  に質問  >  本文

ruby - 数据关联 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
PHP中文网PHP中文网2710日前583

全員に返信(1)返信します

  • PHP中文网

    PHP中文网2017-04-24 09:11:54

    あなたのパートナーとの関係は次のとおりです:

    ドキュメント 1 のセクション
    セクション 1 の段落

    Document と Section は 1 対多の関係を持ち、Section と Paragraph は 1 対多の関係を持ちます。 Document には複数の段落があると結論付けることができますが、それらは直接関連していないため、セクションの関連付けを通じて接続されています。これがトラフのすることです

    返事
    0
  • キャンセル返事