2008年8月24日 星期日

has_and_belongs_to_many, habtm, self referential relationship

http://wiki.rubyonrails.org/rails/pages/HowToCreateASelfReferentialManyToManyRelationship
http://blog.hasmanythrough.com/2007/10/30/self-referential-has-many-through
http://hideto.javaeye.com/blog/75887
http://szeryf.wordpress.com/2007/06/27/self-referential-many-to-many-relations-in-ruby-on-rails/
http://practicalruby.blogspot.com/2007/03/symmetric-self-referential-has-one.html
http://www.aldenta.com/2006/11/10/has_many-through-self-referential-example/
http://blog.handlino.com/2007_05_01_archive.html
http://blog.layer2.org/2007/10/10/convert-has_and_belongs_to_many-to-a-has_many-through-association/
http://www.neyric.com/blog/how-to-delete-a-many-to-many-association-with-rails
http://takol.tw/data/96724670ab3aa3fe6.html

[user model]
has_and_belongs_to_many :friends,
:class_name => "User",
:join_table => "friends",
:association_foreign_key => "friend_id",
:foreign_key => "user_id"

[friend table]
create_table :friends, :id => false do |t|
t.column :user_id, :integer, :null => false
t.column :friend_id, :integer, :null => false
end

[console]
user.friends
[sql]
SELECT * FROM `users` INNER JOIN `friends` ON `users`.id = `friends`.friend_id WHERE (`friends`.user_id = 1 )

沒有留言: