Update_all或update_attribute不更新列
我有一个用户可以通过电子邮件发送的状态报告,我希望在交付操作完成后更新列:sent_mail为true。
def send_status date = Date.today reports = current_user.reports.for_date(date) ReportMailer.status_email(current_user, reports, date).deliver reports.update_all(sent_mail: true) end
和表类
AddSentMailToReports < ActiveRecord::Migration def change add_column :reports, :sent_mail, :boolean, default: false end end
但是,在控制台中,sent_mail仍然设置为false。任何想法为什么这不起作用? 谢谢!
这是因为update_all直接向数据库发送更新 – 它不会更新您在内存中的报表模型。 如果在运行当前版本后检查数据库,则会看到记录已更新。
您需要在每个报告上调用“reload”以从数据库中获取更新版本
reports.map(&:reload)
一次完成所有这些。
如果update_all或update_attribute不起作用,您可以使用它
reports.update_attributes(:sent_mail => true)
参考update_all
, update_attributes
和update_attribute
更改
reports.update_all(sent_mail: true)
至
reports.update_attribute('sent_mail', true)
update_attribute和update_attributes update_attribute vs update_attributes
之间存在差异