【问题标题】:What is the best way to keep temporary version of database while it is being updated in Ruby on Rails?在 Ruby on Rails 中更新数据库临时版本时,最好的方法是什么?
【发布时间】:2020-03-25 09:38:56
【问题描述】:

我目前有一个在 ruby​​ on rails 中存储信息的模型,但我想每小时更新一次此信息。在更新我的数据库时保留数据的临时版本的最佳方法是什么?

我尝试过使用

@temp = Lecture.deep_dup

但是当我从我的数据库中删除所有内容时,这将被清除。

最好的方法是什么?

编辑: 这是进行更新的代码

lecture = Lecture.create(name:course_name,section:section,term:term_name,days:course_days,s_time:start_time,e_time:end_time,location:location,also_reg:also_reg,status:status)
lecture.save

这会在抓取网站时运行几分钟

【问题讨论】:

  • 你能告诉我们每小时更新的代码吗?
  • @lacostenycoder 我在清除数据库后添加了将新数据保存到活动记录的方式,这有帮助吗?
  • 查看我的答案,您可以将代码包装在事务中。但是“清空数据库”?这是在哪里发生的?

标签: ruby-on-rails ruby activerecord model


【解决方案1】:

假设您有一些需要处理所有数据的任务,只需将该代码包装在事务中即可。

根据您的更新进行更新

ActiveRecord::Base.transaction do
  lecture = Lecture.create(
    name: course_name, section: section, term: term_name, days: course_days,
    s_time: start_time, e_time: end_time, location: location, also_reg: also_reg, status: status)
  lecture.save
end

每条评论更新 2 次,在这种情况下最好这样做:

Lecture.transaction do
  lecture = Lecture.create(
    name: course_name, section: section, term: term_name, days: course_days,
    s_time: start_time, e_time: end_time, location: location, also_reg: also_reg, status: status)
    lecture.save
  end
end

https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

但是,如果您的 Lecture.create 方法运行时间很长,我建议您将其移至工作人员/后台作业。见https://guides.rubyonrails.org/active_job_basics.html

【讨论】:

  • Lecture.transaction 更可取。特别是对于多个数据库设置。
猜你喜欢
  • 2010-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 1970-01-01
相关资源
最近更新 更多