2010-09-22 60 views
3

我从表单中传递4个值。还原属性的更改

attr1 
attr2 
attr3 
attr4 

在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 

什么更好的办法来恢复除了一些属性的变化?我想恢复除一个或两个以外的所有属性。

回答

1

这应该工作,但是如果你只是做一对夫妇领域,我不明白你为什么会不只是他们写出来明确

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

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

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

我不想返回错误。无声地,我只想用最后的价值恢复它。 – 2010-09-22 19:31:49