Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails many to many self join

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!

like image 965
awex Avatar asked Aug 03 '10 13:08

awex


2 Answers

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
like image 123
Ju Nogueira Avatar answered Oct 19 '22 07:10

Ju Nogueira


If it doesn't make too much sense to create another class to join the two, an alternative approach could be:

class Word < ActiveRecord::Base 
  has_and_belongs_to_many :synonyms, class_name: "Word", 
                                     join_table: "word_synonyms",
                                     association_foreign_key: "synonym_id"
end

The join table would look like this:

create_table :word_synonyms do |t|
  t.integer :word_id
  t.integer :synonym_id
end
like image 39
Ibrahim Muhammad Avatar answered Oct 19 '22 07:10

Ibrahim Muhammad