How to find and remove part of a string in Rails Console - ActiveRecord -
i'm looking way in rails console find values finish particular string , remove string value.
something along lines of:
model.all.each{|x| x.duration.slice!(" weeks")}.where("duration not null")
so values such "47 weeks" become "47", there isn't slice method activerecord/activemodel
, don't know equivalent.
any ideas??
thanks in advance...
you can use where("column_name <matcher>")
syntax search models column having matching substring:
matching_models = model.where("duration '% weeks'")
then iterate on result, using gsub
replace column value
matching_models.find_each |model| model.update_column(:duration, model.duration.gsub(/ weeks$/, "") end
some relevant points:
use
find_each
instead ofeach
load data in batches better use memory.gsub
used replace existing string./ weeks$/
regex matches strings ending in " weeks".model.update_column
used instead ofupdate_attributes
bypassactiverecord
validations , callbacks. can useupdate_attributes
if want run validations , callbacks.
Comments
Post a Comment