【问题标题】:Why getting active record error when trying to work on arrays?为什么在尝试处理阵列时出现活动记录错误?
【发布时间】:2010-05-19 21:21:42
【问题描述】:

我的用户模型中有以下关联:

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

我的 user_users 表中有以下唯一性约束:

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

在我的代码中,我正在检索用户的朋友 --> friends = user.friends。朋友是一个数组。

我有一个场景,我想将带有所有这些朋友的用户添加到朋友数组中。例如:

friends << user

但是,我收到以下错误:

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

什么给了?

【问题讨论】:

  • friendsuser.friends。行。所以您尝试将user 添加为他自己的friend
  • 是的。如果我试图保存到数据库,我希望抛出一个异常。但是,我只想将用户自己添加到他的朋友数组中,作为我想传递给控制器​​的一些业务逻辑的一部分。不保存到数据库。
  • 做朋友

标签: ruby-on-rails arrays activerecord unique-constraint


【解决方案1】:

如果我理解正确,您正在尝试将user 添加为user 的朋友,即您在user_with_all_those_homies 中有user.id

我相信以下方法可以解决您的问题:

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

编辑

好的,现在我明白了:]

在保存到数据库之前,从friends 数组中删除user

friends.reject{ |f| f.id == user.id }

【讨论】:

  • user_with_all_those_homies 不是数组。
猜你喜欢
  • 2018-01-15
  • 1970-01-01
  • 2016-08-03
  • 2011-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-08
  • 2014-08-27
相关资源
最近更新 更多