Ruby on rails, Change a column value when updating a different column value

I have two columns connected to each other in the Rails model:

Article.body Article.body_updated_on 

I want to change Article.body_updated_on to Time.now , every time Article.body updated. If there should be nothing other updated fields.

+4
source share
2 answers

Just add before saving the callback to the article model

 class Article < ActiveRecord:Base before_save :update_body_modified private # <--- at bottom of model def update_body_modified self.body_updated_on = Time.now if body_changed? end end 
+15
source

You can either override the default installer for the body, or even better, use callback to install it just before the update. You can choose one of several options: before_save, before_update ... depending on when you want.

  before_save do |article| article.body_updated_on = Time.now if article.body_changed? end 
+1
source

Source: https://habr.com/ru/post/1433915/


All Articles