views:

43

answers:

1

Hi,

could some one point me to the right direction:

I try to build a model for rails that build up the following:

ClassA -id

ClassA has a relation to many "ClassA" (so it is a reference to itself)

I am searching for the migration and the model.

I a not sure what the correct join table is (I think its a simple 2 columns table ClassA_id, ClassARel_ID -> both point to ClassA) and how to build the model

Thanks!

A: 

I'd use something like

class Person < ActiveRecord::Base
   has_many :friendships, :foreign_key => "person_id", 
      :class_name => "Friendship"

   has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
   belongs_to :person, :foreign_key => "person_id", :class_name => "Person"
   belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person"  
end

And the tables would be like

people: id; name; whatever-you-need    
friendships: id; person_id; friend_id
j.
thank you, just a question to understand the background:how does rails know that belongs_to :friend, :foreign_key => "friend_id", :class_name => "Person" is defined in the friendships table (the field friend_id) ?
awex
I'm not sure I understood your question. As we can read in railsapi.com, "the mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases". And this is the case here, because of the class and table names.
j.