ruby - 数据关联 through,到底用什么用?
PHP中文网
PHP中文网 2017-04-24 09:09:54
0
1
613

有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中文网

认证高级PHP讲师

reply all(1)
洪涛

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!