开发者

Why getting active record error when trying to work on arrays?

开发者 https://www.devze.com 2022-12-30 18:00 出处:网络
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 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?


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 }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号