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 of each load data in batches better use memory.

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

  • model.update_column used instead of update_attributes bypass activerecord validations , callbacks. can use update_attributes if want run validations , callbacks.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -