How to define relationship for user-to-user friendship


#1

Was wondering how I would define this relationship in my User model if:
A friendship relationship consists of two users.


#2

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 W.


#3

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-referential-through

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-join-model-creation


Josh S.
http://blog.hasmanythrough.com