简体   繁体   English

Rails Rake任务更改数据库中的列值

[英]Rails rake task to change column values in database

A tabel in my pgsql database has a column named "duration" which currently stores a string such as.. "5m 21s".. meaning 5 minutes and 21 seconds. 我的pgsql数据库中的表格有一个名为“ duration”的列,该列当前存储一个字符串,例如..“ 5m 21s” ..表示5分21秒。

I am creating a rake task to reformat these to just be the total amount of seconds. 我正在创建一个rake任务,以将其重新格式化为秒总数。

So "5m 21s" would become "321". 因此,“ 5m 21s”将变为“ 321”。

... right now I could write something such as this but I am unsure how to build the query itself. ...现在我可以编写类似这样的内容,但是我不确定如何构建查询本身。

desc 'Change call duration format'
task calls_format_fix: :environment do

    # Service::CallsReport.where('duration')... 
    # all nums before 'm' * 60 + nums before 's'.. then remove all alpha characters.. (do this with regex? ([0-9]*)m\s+([0-9]*)s)

end

Figured it out! 弄清楚了! This is my code and query with comments of what I am doing to achieve changing the column values. 这是我的代码和查询,其中包含关于实现更改列值的操作的注释。 Not sure that this is the best solution but it works! 不确定这是最好的解决方案,但是它能起作用!

desc 'Change call duration format from minutes and seconds to just seconds' 
task calls_reformat: :environment do

   #store all calls in durationValues
   durationValues = Service::CallsReport.all

   #loop through each as 'call'
   durationValues.each do |call|

     #regex to capture minutes and seconds
     call.duration.match(/([0-9]*)m\s+([0-9]*)s/)

     #store the first match ($1) and multiply it by 60 in minToSec
     minToSec = $1.to_i * 60

     #add minToSec to matched seconds from regex ($2)
     totalValue = minToSec + $2.to_i

     #update the value of call duration
     call.update(duration: totalValue)
   end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM