Forum: Ruby on Rails Self-referential MtoM implementation

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.
Ana B. (Guest)
on 2006-05-02 04:48
ok, guys i have followed the self referential recipe from the book it
works perfect but now i have some doubts, at the end the model are
modified to force the user beign added as a friend that add too who are
adding him so how i can make that the full relationship doesn´t be
complete until the friend beign added approves it(talking in the
implementation of the code of course)?

by the way, here is the code:

class AddPeopleAndTheirFriendsRelationship < ActiveRecord::Migration
  def self.up
    create_table :people do |t|
      t.column "name", :string
    end
    create_table :friends_people do |t|
      t.column "person_id", :integer
      t.column "friend_id", :integer
    end
  end
  def self.down
    drop_table :people
    drop_table :friends_people
  end
end

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",
    :after_add => :be_friendly_to_friend,
    :after_remove => :no_more_mr_nice_guy
  def be_friendly_to_friend(friend)
    friend.friends << self unless friend.friends.include?(self)
  end
  def no_more_mr_nice_guy(friend)
    friend.friends.delete(self) rescue nil
  end
end
This topic is locked and can not be replied to.