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
on 2006-04-20 11:52
on 2006-04-20 12:09
Hi, This example is right out of the Rails Recipes book by Chad F. (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
on 2006-04-20 12:17
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"