Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails, Change column value on update of other column value

I have two columns related to each other in a Rails model:

Article.body
Article.body_updated_on

I want to change the Article.body_updated_on to Time.now, every time Article.body is updated. If any other fields updated nothing needs to be happen.

like image 922
geekdeepak Avatar asked Sep 13 '12 00:09

geekdeepak


2 Answers

Just add before save callback to your 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
like image 85
Nick Kugaevsky Avatar answered Oct 22 '22 13:10

Nick Kugaevsky


You can either override the default setter for body, or better yet, use a callback to set it just before update. You could choose from several options: before_save, before_update ... depending on exactly when you want it.

 before_save do |article|
   article.body_updated_on = Time.now if article.body_changed?
 end
like image 1
DGM Avatar answered Oct 22 '22 12:10

DGM