I am passing 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 except some attributes ?? I want to revert all the attributes except one or two ..
This should work, but if you're only doing it on a couple fields, I don't see why you wouldn't just write them out explicitly
def before_validation
if condition == true
for x in [:attr1, :attr2, :attr3]
self.send("#{x}=", send("#{x}_was")
end
return false
end
end
Are there attributes that can be changed if condition == true
, if not you can just abort the saving in making the object invalid. You could do it like this:
class YourModel < ActiveRecord::Base
def validate
if condition = true
errors.add(:base,"condition is true")
return false
end
end
end
精彩评论