mysql - 导轨 : Querying with an Array

标签 mysql ruby-on-rails-3

我有以下创建并执行 SQL 查询的方法:

def edition_authors(edition, authors)
  query_string = "contributor_type = ? AND author = ?"
  for i in 1..authors.length - 1
    query_string += " OR author = ?"
  end
  return edition.contributors.where(query_string, 'Author', authors)
end

最后一行是我遇到的麻烦。我希望“作者”数组以某种方式变成一组字符串。例如,如果 authors 数组包含 ['James Joyce', 'Cory Doctorow', 'Cormac McCarthy'],我希望最后一行读起来像:

return edition.contributors.where(query_string, 'Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy')

我怎样才能做到这一点?

最佳答案

取决于您使用的是哪种 rails 和哪种 ruby​​,

  1. ActiveRecord 在 Rails 3 中已经有了这个功能:Model.where(:my_field => ['Author', 'James Joyce', 'Cory Doctorow', 'Cormac McCarthy'])

  2. arr.map{|v| v.to_s.inspect 会给你一个逗号分隔的列表

  3. arr.join(',') 会给你一个逗号分隔的列表,没有引号。

然后你可以随意使用这个字符串。

关于mysql - 导轨 : Querying with an Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13390216/

相关文章:

mysql - 按计数选择行组?

windows - 我如何杀死 rails webrick 服务器?

ruby-on-rails - 在 Rails 中使用 jquery 和 Ajax 检查用户名可用性

mongodb - 最佳实践 Mongoid :NestedResources

ruby-on-rails - 如何在 erb 文件中打印包含换行符的字符串

php - 如何显示具体到mysql数据库

mysql - 将此查询转换为 Eloquent

PHP登录-使用SQL语句检测用户类型

php - 通过 $_GET 激活帐户的正确方法是什么?

ruby-on-rails-3 - highcharts 显示在我的渲染 html 页面中,我想使用 Rails 中的 wkhtmltopdf 将其转换为 PDF