Rails update attribute in Model

Terng Gio picture Terng Gio · Oct 24, 2017 · Viewed 10.1k times · Source

I want to update the :position_status in the model based on if :position_date which is equal Date.today, let say I have the :position_date which is Mon, 26 Oct 2017 stored in the database, if the Date.today is on that particular date, then update the :position_status

I have tried to change the position_date to today date to see if it will update or not, but the :position_date was not updated.

attr_accessor :update_position_status

def update_position_status
 if Date.today == self.position_date
  self.update_attribute(:position_status => 'Filled')
 end
end

Answer

max picture max · Oct 24, 2017

update_attribute(name, value) http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-update_attribute

update_attribute updates a single attribute and skips validations. update_attributes takes a hash of attributes and performs validations.

So the corrected code would be:

def update_position_status!
  update_attribute(:position_status, 'Filled') if self.position_date.today?
end

The name should end with ! since it mutates (changes) the object.

However updating the records one by one is not a particularly scalable solution. Instead you want to select the all the records by date and do a mass update:

# MySQL    
Thing.where("DATE(position_date)=CURDATE()")
     .update_all(position_status: 'Filled')

# Postgres
Thing.where("date_trunc('day', position_date) = current_date()")
     .update_all(position_status: 'Filled')