新手问题 数据关联 through,到底用什么用?为什么我感觉是多余的。

drine · 2015年03月23日 · 最后由 317583395 回复于 2015年03月24日 · 2329 次阅读

有 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

class Document < ActiveRecord::Base
    has_many :sections
    has_many :paragraphs, through: :sections
end

应该是这样的吧?

has_many :sections, through: :sections 你这样写就无限递归了

其实一个 ManyToOne 就足够了,OneToOne 是 ManyToOne 的特殊情况,ManyToMany 可以用 ManyToOne 组合出来,并且更容易理解

#1 楼 @blacktulip 嗯,对,我改过来了..

#3 楼 @drine 还有,has_many :sections,section 里不写 belongs_to document,应该没什么影响的吧?一个 has_many 不已经说明了这两表的关系么。

#4 楼 @drine 若你不需要反过来查到关联,可以不写;belongs_to 添加了以下一些方法:

A Post class declares belongs_to :author, which will add:

    Post#author (similar to Author.find(author_id))

    Post#author=(author) (similar to post.author_id = author.id)

    Post#build_author (similar to post.author = Author.new)

    Post#create_author (similar to post.author = Author.new; post.author.save; post.author)

    Post#create_author! (similar to post.author = Author.new; post.author.save!; post.author)

需要 登录 后方可回复, 如果你还没有账号请 注册新账号