self-referential habtm relationship

I have been working on making a self-referential habtm relationship that
uses a join model because I want to store info about the relationship. I
have been using Chad Fowler's "Rails Recipes" as a guide. So far I have
had little luck. Here is what I have that works a little, but not
really:

class User < ActiveRecord::Base
  has_and_belongs_to_many :friends,
    :class_name=>'User',
    :join_table=>'friends',
    :association_foreign_key=>'friend_id',
    :foreign_key=>'user_id',
    :before_add => :check_self,
    :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

  def check_self(friend)
    if self==friend then ...
  end
end

I want to prevent duplicate entries. When I do something like this

u1=User.find(1)
u2=User.find(2)

u1.friends<<u2.friends

Then it is adding all the friends of u2 even if some of them were
already there.
And it is also adding itself as friend.

Can anyone tell me what I can write in before_add callback so that I can
prevent record from creation if it is meeting some condition.

Thanks
Dharmarth

Dharmarth Shah wrote:

u1=User.find(1)
u2=User.find(2)

u1.friends<<u2.friends

Then it is adding all the friends of u2 even if some of them were
already there.
And it is also adding itself as friend.

Can anyone tell me what I can write in before_add callback so that I can
prevent record from creation if it is meeting some condition.

Thanks
Dharmarth

friends_to_add = (u2.friends - u1.friends)
friends_to_add.delete u1
friends_to_add.each {|f| u1.friends << f}

hth

ilan

Ilan Berci wrote:

Dharmarth Shah wrote:

u1=User.find(1)
u2=User.find(2)

u1.friends<<u2.friends

Then it is adding all the friends of u2 even if some of them were
already there.
And it is also adding itself as friend.

Can anyone tell me what I can write in before_add callback so that I can
prevent record from creation if it is meeting some condition.

Thanks
Dharmarth

friends_to_add = (u2.friends - u1.friends)
friends_to_add.delete u1
friends_to_add.each {|f| u1.friends << f}

hth

ilan

Thank you very much ilan.

Is there any way so that i can throw an exception from before_add
callback and stop record creation??
Because, if i have to repeate this thing every time then it is not
DRY...

Thanks
Dharmarth