2

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!

Salil
  • 46,566
  • 21
  • 122
  • 156
Bogdan Popa
  • 1,099
  • 1
  • 16
  • 37

3 Answers3

7

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.

griswoldbar
  • 499
  • 3
  • 10
0

If update_all or update_attribute does not work you can use this

reports.update_attributes(:sent_mail => true)
Dipak Panchal
  • 5,996
  • 4
  • 32
  • 68
  • it still doesn't work..I was wondering to change it into Object.save != true – Bogdan Popa Sep 26 '12 at 10:55
  • see this link. http://apidock.com/rails/ActiveRecord/Base/update_all/class and use it - reports.update_all(:send_mail => true) -- check logs in background if possible send that logs – Dipak Panchal Sep 26 '12 at 11:52
-1

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

Community
  • 1
  • 1
Salil
  • 46,566
  • 21
  • 122
  • 156