I have a data set that I'm trying to sort alphabetically. A lot of records have a "the" at the beginning. 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").
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):
records = Record.where("lower(title) LIKE :prefix", prefix: "#{the}%")
Then use sub to replace the "the", then update the records:
records.each do |r|
r.title = r.title.sub(/the/i, "")
r.title = "#{r.title}, The"
r.save
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.