Search code examples
ruby-on-railsassociationsmodel-associations

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. 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. 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 :

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

although there is an idea with id = 66.

I am clearly unsure of the right way to use the :foreign_key in associations linking a model to itself. Would someone please have tips ?


Solution

  • Get rid of the :foreign_key => "idea_id" on the 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).