Update_all or update_attribute doesn't update

2019-06-03 06:55发布

I have a status report a user can send by email and I want to update a column :sent_mail to true, after the deliver action is completed.

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

and the table class

AddSentMailToReports < ActiveRecord::Migration
  def change
    add_column :reports, :sent_mail, :boolean, default: false
  end
end

However, in console, sent_mail is still set to false.Any ideas why this doesn't work? Thanks!

3条回答
▲ chillily
2楼-- · 2019-06-03 07:12

If update_all or update_attribute does not work you can use this

reports.update_attributes(:sent_mail => true)
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-06-03 07:19

This is because update_all sends an update directly to the database - it won't update the report models you have in memory. If you check the database after running your current version, you'll see that the records have been updated.

You need to call 'reload' on each report to get the updated version from the database or

reports.map(&:reload)

to do them all in one go.

查看更多
Fickle 薄情
4楼-- · 2019-06-03 07:27

Ref update_all, update_attributes and update_attribute

Change

reports.update_all(sent_mail: true)

To

reports.update_attribute('sent_mail', true)

There is difference between update_attribute and update_attributes update_attribute vs update_attributes

查看更多
登录 后发表回答