繁体   English   中英

查询以“ The”开头的记录,并将“ The”移至字符串的末尾,并在Rails Postgres中加入逗号

[英]Query for Records beginning with “The” and move “The” the end of a string and join with a comma in Rails Postgres

我有一个要按字母顺序排序的数据集。 许多记录的开头都有一个“ the”。 我想用“ The”(即爱尔兰酒吧)查询记录,并将“ The”移到字符串的末尾并用逗号联接(即“ Irish Bar”)。

我觉得这应该是要查询然后更新的正则表达式。 似乎有点不客气,必须有一个优雅的解决方案,因为这并非不常见的要求。

regexp = \w+[The]  (?????)
records = Record.where("title LIKE ?", regexp)

records.each do |record|
  record.title = "title witthou the the + ", The"
  record.save
end

您可以使用它来查找以“ the”开头(不区分大小写的记录)的记录:

records = Record.where("lower(title) LIKE :prefix", prefix: "#{the}%")

然后使用sub替换“ the”,然后更新记录:

records.each do |r|
  r.title = r.title.sub(/the/i, "")
  r.title = "#{r.title}, The"
  r.save
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM