[英]How to declare associations in a Ruby on Rails model associated to itself?
In my Ruby on Rails app, I have an Idea model with a father_id attribute. 在我的Ruby on Rails应用程序中,我具有一个带有Father_id属性的Idea模型。 The model definition declares the following associations : 模型定义声明以下关联:
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
I think I got them wrong because when I use the rails console, I can call the children of an idea but not its father. 我认为我弄错了它们,因为当我使用Rails控制台时,我可以称呼某个想法的孩子,但不能称呼它的父亲。 For example : 例如 :
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>]
which means that calling the children through the associations works fine. 这意味着通过协会打电话给孩子们很好。 But calling the father returns nil : 但是打电话给父亲返回nil:
irb(main):010:0> i.father
=> nil
although there is an idea with id = 66. 尽管有一个ID = 66的想法。
I am clearly unsure of the right way to use the :foreign_key in associations linking a model to itself. 我显然不确定在将模型链接到自身的关联中使用:foreign_key的正确方法。 Would someone please have tips ? 有人可以给我提示吗?
Get rid of the :foreign_key => "idea_id"
on the belongs_to
: 摆脱了:foreign_key => "idea_id"
的belongs_to
:
belongs_to :father, :class_name => "Idea"
has_many :children, :class_name => "Idea", :foreign_key => "father_id", :dependent => :destroy
(You could change it to "father_id"
, which is what you want, but that's the default so there's really no need to specify it). (您可以将其更改为"father_id"
,这是您想要的,但这是默认设置,因此实际上无需指定它)。
Remove both foreign_key specifications 删除两个foreign_key规范
belongs_to :father, :class_name => "Idea"
has_many :children, :class_name => "Idea", :dependent => :destroy
And, make sure you have a migration which adds father_id
in ideas
. 而且,请确保您有增加了一个迁移father_id
的ideas
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.