Forum: Ruby on Rails How to define relationship for user-to-user friendship

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
A4db55c902838cdd809942c4dc05abd8?d=identicon&s=25 Jesse (Guest)
on 2007-03-08 12:43
Was wondering how I would define this relationship in my User model if:
A friendship relationship consists of two users.
Dfd6f9989147955682701da8227df8b4?d=identicon&s=25 Michael Wang (Guest)
on 2007-03-08 13:07
(Received via mailing list)
Jesse wrote:
> Was wondering how I would define this relationship in my User model if:
> A friendship relationship consists of two users.

class CreateUsers < ActiveRecord::Migration
   def self.up
     create_table :users do |t|
       t.column :name, :string, :limit => 80, :null => false
       t.column :friend_id, :integer
     end
   end

   def self.down
     drop_table :users
   end
end


class User < ActiveRecord::Base

   belongs_to :friend,
              :class_name => "User",
              :foreign_key => "friend_id"

end


[276]script/console
Loading development environment.
 >> john = User.create(:id => 1, :name => "John")
 >> jane = User.create(:id => 2, :name => "Jane")
 >> john.friend = jane
 >> jane.friend = john
 >> john.friend_id
=> 2
 >> jane.friend_id
=> 1


--
Michael Wang
9f0f89bbd9e1ecfbaab6584e429b7a2f?d=identicon&s=25 Josh Susser (jsusser)
on 2007-03-08 20:16
Jesse wrote:
> Was wondering how I would define this relationship in my User model if:
> A friendship relationship consists of two users.

You'll want to set up a self-referential many-to-many relationship.  For
that you'll need two models, User and Friendship (the join model). You
can base it on the example I show in this article:

http://blog.hasmanythrough.com/2006/4/21/self-refe...

Map Node to User, Edge to Friendship. Change the association names as
makes sense for your models. You may also want to read this article:

http://blog.hasmanythrough.com/2006/8/19/magic-joi...

--
Josh Susser
http://blog.hasmanythrough.com
This topic is locked and can not be replied to.