liang gao
2006-Apr-20 07:53 UTC
[Rails] table that have many-to-may relationship to itself
In a social netowrk data model, users belongs other users, and can have many friends as users, so it is a many to many relatioship. the class definition could be class User < ApplicationController has_mang_ang_belongs_to users But how it looks like in the mysql database tables in a "joined" users table. The question really is: what is the table looks like when a model has many and belongs itself. thx -- Posted via http://www.ruby-forum.com/.
Brian Ford
2006-Apr-20 08:10 UTC
[Rails] Re: table that have many-to-may relationship to itself
Hi,
This example is right out of the Rails Recipes book by Chad Fowler
(http://www.pragmaticprogrammer.com/titles/fr_rr/index.html):
Assume that you have people and people have friends. Just as you''ve
described, this is a habtm relationship that refers back to the same
table. Whenever you have a habtm, you need a join table. Here''s a
(partial) migration that describes the two tables:
create_table :people do |t|
t.column "name", :string
end
create_table :friends_people, :id => false do |t|
t.column "person_id", :integer
t.column "friend_id", :integer
end
And now here is the ActiveRecord model:
class Person < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => "Person",
:join_table => "friends_people",
:association_foreign_key => "friend_id",
:foreign_key => "person_id"
end
brian
--
Posted via http://www.ruby-forum.com/.
You''re talking about a self-referential many-many relationship. The Rails Recipes book has an example of how to do this, plus there are a few other things in various places. Try googling "ruby rails self-referential" liang gao wrote:> In a social netowrk data model, users belongs other users, and can have > many friends as users, so it is a many to many relatioship. > > the class definition could be > > class User < ApplicationController > has_mang_ang_belongs_to users > > > But how it looks like in the mysql database tables in a "joined" users > table. > > The question really is: what is the table looks like when a model has > many and belongs itself. > > thx > >