简体   繁体   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

I have a data set that I'm trying to sort alphabetically. 我有一个要按字母顺序排序的数据集。 A lot of records have a "the" at the beginning. 许多记录的开头都有一个“ the”。 I'd like to query for records with a "The" (ie. The Irish Bar) and move the "The" to the end of the string and join with a comma (ie, "Irish Bar"). 我想用“ The”(即爱尔兰酒吧)查询记录,并将“ The”移到字符串的末尾并用逗号联接(即“ Irish Bar”)。

I feel like this should be a Regular Expression to query and then updating. 我觉得这应该是要查询然后更新的正则表达式。 It seems a bit hacky, there must be an elegant solution as it's not an uncommon requirement. 似乎有点不客气,必须有一个优雅的解决方案,因为这并非不常见的要求。

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

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

You can use this to find records beginning with "the" (edited for case-insensitive): 您可以使用它来查找以“ the”开头(不区分大小写的记录)的记录:

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

Then use sub to replace the "the", then update the records: 然后使用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