2013-03-29 99 views
1

在我的Ruby on Rails应用程序中,我有一个带有father_id属性的Idea模型。 模型定义声明了以下关联:如何在与自身关联的Ruby on Rails模型中声明关联?

class Idea < ActiveRecord::Base 
    belongs_to :father, :class_name => "Idea", :foreign_key => "idea_id" 
    has_many :children, :class_name => "Idea", :foreign_key => "father_id", :dependent => :destroy 

我觉得我得到了他们是错的,因为当我使用的铁轨控制台,我可以叫一个想法的孩子,但不是它的父亲。例如:

irb(main):008:0> i = Idea.find(75) 
=> #<Idea id: 75, father_id: 66> 

irb(main):009:0> i.children 
=> [#<Idea id: 98, father_id: 75>, #<Idea id: 99, father_id: 75>] 

这意味着通过关联调用儿童可以正常工作。虽然有一个id = 66

一个想法,我清楚地确定要使用的正确的方式

irb(main):010:0> i.father 
=> nil 

:foreign_key模型中的链接到自己的关联 但调用的父亲返回零。会有人请小费吗?

+0

你可以看看[祖先](https://github.com/stefankroes/ancestry)。看起来它具有你想要的功能。 – Arjan

+0

只是看了一下。谢谢你的建议,它的确如此。我会尝试使用它,因为我真的可以使用它的一些特性(例如子树,子树到一定的深度等等)。 – Pierre

回答

0

坐上belongs_to摆脱:foreign_key => "idea_id"的:

belongs_to :father, :class_name => "Idea" 
has_many :children, :class_name => "Idea", :foreign_key => "father_id", :dependent => :destroy 

(你可以将其更改为"father_id",这是你想要的,但是这是默认所以真的没有必要指定它)。

+0

非常感谢Andrew,它现在可以工作。我很想完全理解在这种情况下使用':foreign_key',实际上! 1.我知道为什么它不适用于'belongs_to:father,:class_name =>“Idea”,:foreign_key =>“idea_id”',因为在给定记录中,它是属性'father_id'而不是'idea_id'指的是它所属的记录(即它的父亲)。 2.我也明白,正如你所说的,rails基于'belongs_to'后面的':father',将外键默认为'father_id'。 – Pierre

+0

现在,3.我想知道当我声明'has_many:children,:class_name =>“Idea”,:foreign_key =>“father_id”,:dependent =>:destroy'时我是否真的得到了正确的答案。有':foreign_key =>“father_id”'真的需要和正确吗?你在这样一个'belongs_to和has_many'关联的两端总是有相同的外键? – Pierre

+0

如果您知道某种方式可以让我在未获得超过15的声誉的情况下为您提供帮助,请告诉我,我很乐意这样做。 – Pierre

0

删除这两个foreign_key规格

belongs_to :father, :class_name => "Idea" 
has_many :children, :class_name => "Idea", :dependent => :destroy 

而且,要确保你有一个迁移这ideas增加father_id

+0

谢谢@Ashish。 'father_id'确实在创建想法表的迁移中定义。你同时删除':foreign_key'规范的建议看起来像是对@Andrew答案的评论的答案......你能解释什么样的情况需要指定外键? – Pierre