如何使用Rails更新昨天创建的所有记录?

时间:2022-06-30 09:27:51

I need to update the info on all records that were created yesterday, for that I created a migration with the following code:

我需要更新昨天创建的所有记录的信息,因为我使用以下代码创建了一个迁移:

class UpdateFbidToVotes < ActiveRecord::Migration
  def up
    Vote.all.each do |v|
      if v.created_at == Date.today-1
        v.fbid = v.fbid + 1
        v.update!
      end
    end
  end
end

This, however, doesn't work. Can you please point me to what am I doing wrong?

但是,这不起作用。你能指点我做错了什么吗?

Thanks!

谢谢!

2 个解决方案

#1


1  

Try:

尝试:

yesterday = 1.day.ago # or Time.now.yesterday
Vote.where(created_at: yesterday.beginning_of_day..yesterday.end_of_day).update_all('fbid = fbid + 1')

Also, migration files are meant for managing table schema, I'd encourage you to move such db update/delete queries to a rake task instead of migration file, such queries are not reversible(i.e. you can not rely on getting the changes back to previous state) and should not be a part of migrations.

此外,迁移文件用于管理表模式,我建议您将此类数据库更新/删除查询移动到rake任务而不是迁移文件,这样的查询是不可逆的(即您不能依赖于将更改恢复到以前的状态)并且不应该是迁移的一部分。

#2


2  

Something like this:

像这样的东西:

Vote.where(created_at: Date.yesterday).update_all('fbid = fbid + 1')

#1


1  

Try:

尝试:

yesterday = 1.day.ago # or Time.now.yesterday
Vote.where(created_at: yesterday.beginning_of_day..yesterday.end_of_day).update_all('fbid = fbid + 1')

Also, migration files are meant for managing table schema, I'd encourage you to move such db update/delete queries to a rake task instead of migration file, such queries are not reversible(i.e. you can not rely on getting the changes back to previous state) and should not be a part of migrations.

此外,迁移文件用于管理表模式,我建议您将此类数据库更新/删除查询移动到rake任务而不是迁移文件,这样的查询是不可逆的(即您不能依赖于将更改恢复到以前的状态)并且不应该是迁移的一部分。

#2


2  

Something like this:

像这样的东西:

Vote.where(created_at: Date.yesterday).update_all('fbid = fbid + 1')