测试 Rails 中的一个关系是否发生了变化 [英] Test if Has One Relationship has Changed in Rails

查看:42
本文介绍了测试 Rails 中的一个关系是否发生了变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用before_save"回调来检测has_one"关系是否发生变化(关系不是关系结束时的模型)?例如,某些事情会像这样:

Is it possible to have a 'before_save' callback that detects if a 'has_one' relationship has changed (the relationship not the model at the end of the relationship)? For example, something that would act like this:

@person.picture = @picture
@person.picture_changed? # true
@person.save
@person.picture_changed? # false

推荐答案

尝试 relation.changed?... 您可能还想研究观察者,这取决于您要完成的任务.

Try relation.changed?... You may also want to look into observers, depending on what you are trying to accomblish.

示例:

class Model < ActiveRecord::Base
  has_one :relation
  before_save :check_relation_changed
  private def check_relation_changed
    do_something if relation.changed?
  end
end

参考:http://ryandaigle.com/articles/2008/3/31/what-s-new-in-edge-rails-dirty-objects

这篇关于测试 Rails 中的一个关系是否发生了变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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