Update_all or update_attribute doesn't update

2019-06-03 06:57发布

问题:

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!

回答1:

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.



回答2:

If update_all or update_attribute does not work you can use this

reports.update_attributes(:sent_mail => true)


回答3:

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