The accepted answer works correctly but will get noticeably slow if you have a few thousand records ending with " weeks" or more, because Rails has to grab and instantiate all matching records from the table.
In general, it is preferable to leave all work to the database engine, if possible, which could be written like this:
Model.where("duration LIKE '% weeks'").
update_all("duration = SUBSTRING(duration, 1, LENGTH(duration) - 6)")
# => UPDATE `models` SET `models`.`duration` = SUBSTRING(duration, 1, LENGTH(duration) - 6) WHERE (duration LIKE '% weeks')
This query will be much more performant and memory efficient if you have lots of records to update. It uses the update_all
Rails method to run the UPDATE query on all matching records in the table and the SUBSTRING
function to shorten the duration
field by 6 characters, which is the length of the " weeks" string.