我有一段代码可以获取我关注的用户的 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/