How to check changed value in before_save callback model?

How do I know the value that the controller set in the before_save callback?

Example:

I have a model with a field url. Before saving, I want to check if the URL has been changed. If so, do some things with both the new and the old URLs.

Is it possible?

+5
source share
4 answers

Try something like this:

before_save { |m| if m.url_changed? ... }

Also see ActiveModel :: Dirty docs

+19
source
  • The best way

before :todo, if: :first_name_or_last_name_changed?

  • and your todomethod

def first_name_or_last_name_changed?
< >   first_name_changed? || last_name_changed? >
< >

+1

, params. , . , .

before_save, ActiveRecord, , .

0

,

#Non-working code
before_save: record_old_value
after_save: record_change

def record_old_value
   @old_value = self.field
end

def record_change
   if @old_value==self.field
      create_record_in_history :old_value => @old_value, :new_value => self.field
   end
end

The reason this didn't work was because we set self.field = new_value, so it is not available in before_save. But the rails have another Active-Record function, for example field_changed , which can be used directly both before_save and after_save. So i ended up with this solution

#working code
after_save :run_function
def run_function
   @old_value = field_was
   if @old_value==self.field
      create_record_in_history :old_value => @old_value, :new_value => self.field
   end
end
0
source

All Articles