Discard attribute changes

I pass 4 values ​​from my form.

attr1
attr2
attr3
attr4

On before_save

def before_save
  if condition == true
    # here i want to revert changes of attributes ...
    # Right now i am doing this for reverting....
    self.attr1 = self.attr1_was
    self.attr2 = self.attr2_was
  end
end 

Any better way to revert changes besides some attributes? I want to return all attributes except one or two.

+3
source share
2 answers

This should work, but if you do it only on a couple of fields, I don’t understand why you just don’t write them explicitly

def before_validation
  if condition == true
    for x in [:attr1, :attr2, :attr3]
      self.send("#{x}=", send("#{x}_was")
    end
    return false
  end
end
+1
source

Are there attributes that can be changed if condition == true, if you cannot just interrupt the save if the object is invalid. You can do it as follows:

class YourModel < ActiveRecord::Base
  def validate
    if condition = true
      errors.add(:base,"condition is true")
      return false
    end
  end
end
+1
source

Source: https://habr.com/ru/post/1766070/


All Articles