1

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

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

我想我弄错了,因为当我使用 rails 控制台时,我可以调用一个想法的孩子而不是它的父亲。例如 :

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>]

这意味着通过协会打电话给孩子们工作正常。但是调用父亲返回 nil :

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

虽然有一个 id = 66 的想法。

我显然不确定在将模型链接到自身的关联中使用 :foreign_key 的正确方法。有人可以给点建议吗?

4

2 回答 2

0

摆脱:foreign_key => "idea_id"belongs_to

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

(您可以将其更改为"father_id",这是您想要的,但这是默认设置,因此实际上不需要指定它)。

于 2013-03-29T11:15:02.453 回答
0

删除两个 foreign_key 规范

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

并且,确保您有一个添加father_idideas.

于 2013-03-29T11:38:04.680 回答