开发者

Test if Has One Relationship has Changed in Rails

开发者 https://www.devze.com 2023-01-21 19:45 出处:网络
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, so

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


Maybe it works with

@person.picture_id_changed?


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

Example:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消