Ruby on Rails,在更新其他列值时更改列值 [英] Ruby on rails, Change column value on update of other column value

查看:73
本文介绍了Ruby on Rails,在更新其他列值时更改列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails模型中,我有两个相互关联的列:

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

Article.body
Article.body_updated_on

我想更改 Article.body_updated_on 每次 Article.body 被更新为 Time.now 。如果更新了其他任何字段,则无需进行任何操作。

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.

推荐答案

只需在保存回调之前添加到Article模型

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

这篇关于Ruby on Rails,在更新其他列值时更改列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆