gpt4 book ai didi

ruby-on-rails - Rails 5 范围像多个部分字符串

转载 作者:太空宇宙 更新时间:2023-11-03 17:28:57 25 4
gpt4 key购买 nike

假设我有这样一个范围:

scope :by_templates, ->(t) { joins(:template).where('templates.label ~* ?', t) }

如何使用 t 检索多个模板?

Document.first.by_templates(%w[email facebook])

此代码返回此错误。

PG::DatatypeMismatch: ERROR:  argument of AND must be type boolean, not type record
LINE 1: ...template_id" WHERE "documents"."user_id" = $1 AND (templates...

最佳答案

PostgreSQL 允许您使用 op any(array_expr) construct 将 bool 值运算符应用于整个值数组。 :

9.23.3. ANY/SOME (array)

expression operator ANY (array expression)
expression operator SOME (array expression)

The right-hand side is a parenthesized expression, which must yield an array value. The left-hand expression is evaluated and compared to each element of the array using the given operator, which must yield a Boolean result. The result of ANY is “true” if any true result is obtained. The result is “false” if no true result is found (including the case where the array has zero elements).

PostgreSQL 还支持 array constructor syntax用于创建数组:

array[value, value, ...]

方便的是,当值为数组时,ActiveRecord 会将占位符扩展为逗号分隔列表。

把这些放在一起给我们:

scope :by_templates, ->(templates) { joins(:template).where('templates.label ~* any(array[?])', templates) }

顺便说一句,如果您使用不区分大小写的正则表达式运算符 ( ~* ) 作为不区分大小写的比较(即没有进行真正的正则表达式模式匹配),那么您可能需要使用 upper相反:

# Yes, this class method is still a scope.
def self.by_templates(templates)
joins(:template).where('upper(templates.label) = any(array[?])', templates.map(&:upcase) }
end

然后你可以添加一个索引到templatesupper(label)加快速度并避免 templates 中的杂散正则表达式元字符可能出现的问题.由于奇怪的谎言 'ß'.upcase,我倾向于对这类事情使用大写字母正在'SS'但是'SS'.downcase正在'ss' .

关于ruby-on-rails - Rails 5 范围像多个部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53715898/

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