views:

32

answers:

1

I have the following association in my User model:

has_and_belongs_to_many :friends, :class_name => 'User', :foreign_key => 'friend_id'

I have the following uniqueness constraint in my user_users table:

UNIQUE KEY `no_duplicate_friends` (`user_id`,`friend_id`)

In my code, I am retrieving a user's friends --> friends = user.friends. friends is an array.

I have a scenario where I want add the user with all those friends to the friends array. Ex:

friends << user

However, I get the following error:

ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '18-18' for key 'no_duplicate_friends': INSERT INTO `users_users` (`friend_id`, `user_id`) VALUES (18, 18)

What gives?

A: 

If I understood it correctly, you are trying to add useras a friend of user, ie, you have user.id in user_with_all_those_homies.

I believe something like the following may solve your problem:

# assuming user_with_all_those_homies is an array of users
user_with_all_those_homies.reject{ |u| u.id == user.id }

Edit

Ok, now i understood :]

Before saving to the database, remove the user from friends array:

friends.reject{ |f| f.id == user.id }
j.
user_with_all_those_homies is not an array.
keruilin