Search code examples
ruby-on-railsactiverecordactivemodelrails-console

How to find and remove part of a string in Rails Console - ActiveRecord


I'm looking for a way in the rails console to find any values that finish with a particular string and remove that string from the value.

Something along the lines of:

Model.all.each{|x| x.duration.slice!(" weeks")}.where("duration IS NOT NULL") 

So that values such as "47 weeks" simply become "47", but there isn't a Slice method for ActiveRecord/ActiveModel and I don't know the equivalent.

Any ideas??

Thanks in advance...


Solution

  • You can use where("column_name LIKE <matcher>") syntax to search for models with the column having the matching substring:

    matching_models = Model.where("duration LIKE '% weeks'")
    

    Then iterate over the result, using gsub to replace the column value

    matching_models.find_each do |model|
      model.update_column(:duration, model.duration.gsub(/ weeks$/, "")
    end
    

    Some relevant points:

    • Use find_each instead of each as it will load data in batches to better use memory.

    • gsub is used to replace the existing string. The / weeks$/ regex matches strings ending in " weeks".

    • model.update_column is used instead of update_attributes to bypass ActiveRecord validations and callbacks. You can use update_attributes if you want to run validations and callbacks.