mysql - 需要将数组转换为整数以用于 Rails API 中的 MySQL 查询

标签 mysql ruby-on-rails ruby

我有一段代码可以获取我关注的用户的 ID 列表。

@followed = current_user.followed_user_ids

它给了我这样的结果 [11,3,24,42]

我需要将这些添加到 NOT IN mysql 查询中。 目前,我得到的是 NOT IN ([11,3,24,42]),这会引发错误。我需要 NOT IN (11,3,24,42)

这是 find_by_sql 语句的一部分,因此在这一点上我无法使用 where.not

最佳答案

在 rails 4 中:

@followed = current_user.followed_user_ids # @followed = [11,3,24,42]
@not_followed = User.where.not(id: @followed)

这应该生成类似于 select * from users where id not in (11,3,24,42)

在您发表评论时,您正在使用 find_by_slq(所有 Rails 版本都提供)。然后你可以使用 join 方法:

query = "select * from users where id not in (#{@followed.join(',')})"

如果 @followed 为空,这将引发 mysql 错误,结果查询将是

select * from users where id not in ()

要解决此问题而无需在代码中指定额外的 if 语句,您可以使用:

query = "select * from users where id not in (0#{@followed.join(',')})"

你的正常查询是这样的:

select * from users where id not in (01,2,3,4)

但如果数组为空则结果为

select * from users where id not in (0)

这仍然是一个有效的 sql 语句并且没有提供任何结果(这可能是您场景中的预期情况)。

关于mysql - 需要将数组转换为整数以用于 Rails API 中的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26502611/

相关文章:

ruby-on-rails - 更新 HABTM 模型关联只会删除关联

ruby-on-rails - 在 Rails 4 中将 SQL 查询转换和优化为 Active Record 查询

ruby - 如何使用 JSON 进行 Ruby 对象序列化

ruby - rbenv:未安装版本 `2.2.3'(由 RBENV_VERSION 环境变量设置)

MySQL 截断挂起

php - 从原始 sql 更改为 codeigniters 事件类

javascript - 使用ajax时工作数据库功能不起作用

java - Eclipse 使用 while 循环将数据插入 MySQL 没有指定值错误

javascript - 如何在 javascript onchange 中显示值?

ruby - 对如何使用模拟和 stub 感到困惑