Update_all or update_attribute doesn't update the column

扶醉桌前 提交于 2019-12-23 03:12:13

问题


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



来源:https://stackoverflow.com/questions/12598435/update-all-or-update-attribute-doesnt-update-the-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!