Question

i am trying to build a model with references to the same model, the problem is that i cant access to the parent and children attributes.

the model is:

class Socio < ActiveRecord::Base
  attr_accessible :socio_padre_id

  belongs_to :socio_padre, :class_name => "Socio", :foreign_key => "socio_id"
  has_many :socios_hijo, :class_name => "Socio" 
end 

when i try to get these attributes at the console i get :

1.9.2p320 :049 >   Socio.last.socio  (tab)
Socio.last.socio                            Socio.last.socio_padre_id?                  Socio.last.socio_path
Socio.last.socio=                           Socio.last.socio_padre_id_before_type_cast  Socio.last.socio_url
Socio.last.socio_ids                        Socio.last.socio_padre_id_change            Socio.last.socios
Socio.last.socio_ids=                       Socio.last.socio_padre_id_changed?          Socio.last.socios=
Socio.last.socio_padre_id                   Socio.last.socio_padre_id_was               Socio.last.socios_path
Socio.last.socio_padre_id=  

1.9.2p320 :049 >   Socio.last.socio_padre
  Socio Load (1.0ms)  SELECT "socios".* FROM "socios" ORDER BY "socios"."id" DESC LIMIT 1
NoMethodError: undefined method `socio_padre' for #<Socio:0x00000004430fe0>

I cant find the solution to my problem, im new with rails. Sorry for my english and Thanks for the help!.

[EDIT] - I try with this relations and works!!

belongs_to :socio_padre, :class_name => "Socio" 
has_many :socios_hijo, :class_name => "Socio" , :foreign_key => "socio_padre_id" 
Was it helpful?

Solution

You can use ancestry gem: https://github.com/stefankroes/ancestry As you want to build a tree data structure. The model should have a parent_id and a child_id.

Other posibility is to use self joins relations: http://guides.rubyonrails.org/association_basics.html#self-joins

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top