簡體   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