【问题标题】:Using array in embedded SQL query in Ruby在 Ruby 的嵌入式 SQL 查询中使用数组
【发布时间】:2013-09-12 09:28:42
【问题描述】:

我通过以下方法收集了一个模型学生的ID

ids = Student.all.map{|s| s.id}

现在我想在我的 Ruby 代码中的以下 sql 查询中使用上述数组 ID,如下所示:

students = repository.adapter.select(%Q{select id, roll_number, major from students where id in (#{ids})})

上面这行给出了语法错误,因为我不能在这个 sql 查询中使用 ids 作为数组。我是 Ruby 和 Mysql 的新手。那么任何人都可以为此提供解决方案吗?

【问题讨论】:

    标签: mysql ruby-on-rails arrays ruby-datamapper


    【解决方案1】:

    你可以这样做

    ids = Student.pluck(:id)
    repository.adapter.select("some fields").where(["id IN (?)", ids])
    

    【讨论】:

    • 它不工作。你能用一个小例子给出一个确切的语法吗?
    • 我刚刚为您提供了一个关于如何在 rails 中使用数组运行查询的示例。我不确定您要做什么
    • 看我写了以下内容:ids = Student.all.map{|s| s.id},pluck 不起作用,但是我按照您的建议编写了以下语句:repository.adapter.select(%Q{select id, name from Students where (["id in (?)",#{ id}])})
    • ??看不到您的评论
    • 我可以看到存储库有适配器,而适配器有学生?有这些关联吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-26
    相关资源
    最近更新 更多