ruby-on-rails - 按字段中的位数查询 Rails

标签 ruby-on-rails postgresql activerecord rails-activerecord

我有一个带有表的 Rails 应用程序:“clients”。客户表有一个字段:电话。电话数据类型是字符串。我正在使用 postgresql。我想编写一个查询,选择电话值包含超过 10 位数字的所有客户。电话没有特定格式:

+1 781-658-2687
+1 (207) 846-3332
2067891111
(345)222-777
123.234.3443
etc.

我一直在尝试以下变体:

Client.where("LENGTH(REGEXP_REPLACE(phone,'[^\d]', '')) > 10")

任何帮助都会很棒。

最佳答案

您几乎拥有它,但是您缺少 regexp_replace'g' 选项,来自 fine manual :

The regexp_replace function provides substitution of new text for substrings that match POSIX regular expression patterns. [...] The flags parameter is an optional text string containing zero or more single-letter flags that change the function's behavior. Flag i specifies case-insensitive matching, while flag g specifies replacement of each matching substring rather than only the first one.

所以 regexp_replace(string, pattern, replacement) 表现得像 Ruby 的 String#subregexp_replace(string, pattern, replacement, 'g') 的行为类似于 Ruby 的 String#gsub

您还需要通过双引号 Ruby 字符串一直到 PostgreSQL 获取 \d,因此您需要说 \\d在你的 ruby 中。当每个人都想使用相同的转义字符时,事情往往会变得一团糟。

这应该做你想做的:

Client.where("LENGTH(REGEXP_REPLACE(phone, '[^\\d]', '', 'g')) > 10")
# --------------------------------------------^^---------^^^

关于ruby-on-rails - 按字段中的位数查询 Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33426432/

相关文章:

ruby-on-rails - 将文件上传到 amazon aws3 Rails,并出现 Carrierwave 错误主机名与服务器证书不匹配

ruby-on-rails - #<Net::HTTP 127.0.0.1:8080 open=false> 的未定义方法 `use_ssl'

ruby-on-rails - 事件记录/Postgres : aggregate functions are not allowed in WHERE

mysql - 在 has_many 上链接 where 子句 :through association (Rails 4. 1.0.rc1)

ruby-on-rails - 理解 ActiveRecord::基类名称

javascript - 使用 Ruby on Rails 剥离 javascript

sql - rails : mixing NOSQL & SQL Databases

sql - 如何在 WHERE 和 HAVING 中查询同一列

sql - 使用 PostgresQL 检查现有列的约束

php - SQL 查找值比指定值集中的每个值最接近的行