0

I try to change attribute_1 value, when I detect attribute_2 is changed and about to get updated.

The object gets updated but the set attribute_1 value is not persisting though, why?

before_update :check_attribute2_change

def check_attribute_2_change
  if attribute_2_changed?
      attribute_1 = nil
  end
end
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

6

Try this:

before_update :check_attribute2_change

def check_attribute_2_change
  self.attribute_1 = nil if attribute_2_changed?      
end
Aaditi Jain
  • 6,969
  • 2
  • 24
  • 26
  • 2
    I didn't know that `self` was so important. – Fellow Stranger Dec 29 '14 at 12:08
  • 2
    `self` here is important to indicate that attribute_1 is actually an attribute of the instance object that you are referring to. Without`self` it was taking `attribute_1` as a variable and hence you were not seeing the results. Hope that clears the reason :) – Aaditi Jain Dec 29 '14 at 12:29
  • The if can also go in the callback declaration like this: `before_update :remove_attribute_1, if: :attribute_2_changed? def remove_attribute_1 self.attribute_1 = nil end` – Remigio Arenas Sep 01 '21 at 20:43
0

If you are on model, call:

save!

You code will look like this:

before_update :check_attribute2_change

def check_attribute_2_change
  if attribute_2_changed?
      attribute_1 = nil
      save!
  end
end

Note that "before_update" callback, is called before your object is saved (persisted) on database. When you change one more attribute at this stage, you need to save it.

WeezHard
  • 1,982
  • 1
  • 16
  • 37
  • Trying your code I get this error message: "stack level too deep". I don't know if it's because I'm using the `update` method (and not `save`) in the controller. – Fellow Stranger Dec 29 '14 at 10:46
  • @Numbers... Sorry, Remove "self." and put only "save" I will update my answer – WeezHard Dec 29 '14 at 10:49
  • 1
    I am doubtful if `save` would work since it will again trigger a before_update callback. Also we generally avoid using `!(bang)` version. See this question: (http://stackoverflow.com/questions/612189/why-are-exclamation-marks-used-in-ruby-methods/612653#612653) – Aaditi Jain Dec 29 '14 at 11:46
  • @AaditiJain I made a confusion with after_save :) – WeezHard Dec 29 '14 at 12:54