还原属性的更改

时间:2010-09-22 19:16:58

标签: ruby-on-rails

我从表单中传递了4个值。

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 

除了某些属性之外还有哪些更好的方法来还原更改?我想恢复除一两个之外的所有属性..

2 个答案:

答案 0 :(得分:1)

是否存在可以更改condition == true的属性,否则您只能在使对象无效时中止保存。你可以这样做:

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

答案 1 :(得分:1)

这应该可行,但是如果你只在几个字段上进行,我不明白为什么你不会只是明确地写出来

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