2010-09-22 61 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