0
User.where('user_id not in (?)', CancelledUser.all.collect(&:id).join(', '))

当没有取消的用户时,上面的查询给了我以下错误。

ActiveRecord::StatementInvalid: TinyTds::Error: 从字符串转换为唯一标识符时转换失败。: EXEC sp_executesql N'SELECT [users].* FROM [userss] WHERE (user_id not in (N''''))'

我该如何解决?

4

1 回答 1

0

您不想加入ids,这将被视为单个字符串文字。尝试以下操作:

User.where('user_id not in (?)', CancelledUser.all.collect(&:id))

更新:

直接在 SQL Server 中执行生成的查询也会产生同样的问题。当您有空数组时,在检索具有空数组的记录时查看问题中的答案以解决相同的问题。

因此,您可以执行以下操作来解决问题:

cancelled_users = CancelledUser.all.collect(&:id)

if cancelled_users.any?
  User.where('user_id not in (?)', cancelled_users)
else
  User.all
end
于 2013-12-05T19:55:23.563 回答