如何检测模型的属性变化? [英] How to detect attribute changes from model?

查看:40
本文介绍了如何检测模型的属性变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 rails 中创建一个回调函数,该函数在模型保存后执行.

I'd like to create a callback function in rails that executes after a model is saved.

我有这个模型,索赔有一个属性状态",它根据索赔的状态而变化,可能的值有待处理、认可、批准、拒绝

I have this model, Claim that has a attribute 'status' which changes depending on the state of the claim, possible values are pending, endorsed, approved, rejected

数据库有'state',默认值为'pending'.

The database has 'state' with the default value of 'pending'.

我想在第一次创建模型或从一个状态更新到另一个状态后执行某些任务,具体取决于它从哪个状态更改.

I'd like to perform certain tasks after the model is created on the first time or updated from one state to another, depending on which state it changes from.

我的想法是在模型中有一个函数:

My idea is to have a function in the model:

    after_save :check_state

    def check_state
      # if status changed from nil to pending (created)
      do this

      # if status changed from pending to approved
      performthistask
     end

我的问题是如何在模型内更改之前检查先前的值?

My question is how do I check for the previous value before the change within the model?

推荐答案

你应该看看 ActiveModel::Dirty 模块:您应该能够对 Claim 模型执行以下操作:

You should look at ActiveModel::Dirty module: You should be able to perform following actions on your Claim model:

claim.status_changed?  # returns true if 'status' attribute has changed
claim.status_was       # returns the previous value of 'status' attribute
claim.status_change    # => ['old value', 'new value'] returns the old and 
                       # new value for 'status' attribute

claim.name = 'Bob'
claim.changed # => ["name"]
claim.changes # => {"name" => ["Bill", "Bob"]}

哦!Rails 的乐趣!

Oh! the joys of Rails!

这篇关于如何检测模型的属性变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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