gpt4 book ai didi

mysql - 导轨 : Querying with an Array

转载 作者:可可西里 更新时间:2023-11-01 07:49:55 28 4
gpt4 key购买 nike

我有以下创建并执行 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com