Test if Has One Relationship has Changed in Rails
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
精彩评论