Newbie trying self-referencing :through via REST model


#1

I’ve read through countless blogs and the docs and can’t seem to get
what I expect. I also tried irc on freenode, but they ignored me. I
must have a case of the mange or something.

I have a Person model (on a people table) and I want a hierarchy of
masters and servants. I’m doing this via a Vassalship model. When I
try to assign a master to a servant like so :

 juniorperson.master=seniorperson

I get NoMethodError: undefined method `update_attributes’ for #<Class:
0x48be738>

And who knows what class that was. I can do
seniorperson.servants<<juniorperson no problem, but then I get a nil
for juniorperson.master ?!?!

My models look like this :

class Person < ActiveRecord::Base

has_many :vassalships,:class_name=>‘Vassalship’,:foreign_key=>:master_id
has_one :master,:through=>:vassalships,:source=>:master;
has_many :servants,:through=>:vassalships,:source=>:servant;
end

class Vassalship < ActiveRecord::Base
belongs_to :master,:class_name=>‘Person’,:foreign_key=>‘master_id’
belongs_to :servant,:class_name=>‘Person’,:foreign_key=>‘servant_id’
end

my tables are here, if you need to see them: http://pastie.org/352858,
and the full console track is here : http://pastie.org/352871

I’m doing something wrong, but I don’t know what. And anyone got a
better idea for the relationship? Vassalship seems a bit obscure.


#2

On Mon, Jan 5, 2009 at 6:14 PM, itsastickup removed_email_address@domain.invalid
wrote:

   belongs_to :master,:class_name=>'Person',:foreign_key=>'master_id'
   belongs_to :servant,:class_name=>'Person',:foreign_key=>'servant_id'

end

You only need one model, Person should suffice:

class Person < ActiveRecord::Base

belongs_to :master, :class_name => ‘Person’, :foreign_key =>
‘master_id’

has_many :servants, :class_name => ‘Person’, :foreign_key =>
‘master_id’

end

Let me know how you get on.

Regards,
Franz


#3

I have a need for REST (as well as other things), as mentioned, and
for that I require the go-between model. In anycase presumably my
original question does have an answer, no? Perhaps :through does not
work self-referentially, although I would be surprised. But the docs
don;t have it and blogs haven’t helped.

On 5 Jan, 22:45, “Franz S.” removed_email_address@domain.invalid wrote:


#4

try:

class Person < ActiveRecord::Base

has_many
:vassalships,:class_name=>‘Vassalship’,:foreign_key=>‘master_id’
has_many :vassalship_belongings, :class_name =>
‘Vassalship’, :foreign_key => ‘slave_id’
has_one :master,:through=>:vassalships,:source=>:person

has_many :servants,:through=>:vassalship_belongings,:source=>:person
end

class Vassalship < ActiveRecord::Base

belongs_to :master,:class_name=>‘Person’,:foreign_key=>‘master_id’

belongs_to :servant,:class_name=>‘Person’,:foreign_key=>‘servant_id’
end