2014-11-08 39 views
0

比方說,你有沒有和年齡屬性的用戶如果試圖更新屬性爲負數驗證將失敗,但實例仍會有負面的年齡值如果驗證失敗,您可以重置ActiveRecord實例嗎?

這不可能是負

class User < ActiveRecord::Base 
    validates :age, numericality: { greater_than: 0 } 
end 

#<User id: 1, age: 5, created_at: "2014-11-08 20:14:12", updated_at: "2014-11-08 20:14:12"> 
user.update_attributes!(:age => -5) 
#<User id: 1, age: -5, created_at: "2014-11-08 20:14:12", updated_at: "2014-11-08 20:14:12"> 

除了捕獲ActiveRecord :: RecordInvalid並重新設置值是否是他們的方式來重置實例,如果其驗證失敗?

的感謝!

回答

2

如果驗證失敗,則可以致電model.reload。因此,它看起來像:

if @model.update_attributes(age: params[:age]) # params[:age] = -5 for example 
    # model is valid and saved, continue... 
else # update_attributes return false and will not raise an exception if model is invalid 
    # model is invalid, reloading... 
    @model.reload 
    # if we call @model.age now, it will return previous value 
end 

反正會的update_attributes設置屬性甚至模型正在成爲更新後無效,但它不會持續無效的屬性數據庫。但請記住它會重置可能在此調用中執行的所有其他更改,因此update_attributes(name: params[:name], age: params[age])將重置名稱和年齡,即使名稱有效。

1

我會說你需要一個自定義的驗證,e.g:

class MyValidator < ActiveModel::Validator 

    def validate(record) 
    unless record.age.to_i > 0 
     record.errors[:name] << 'Invalid!' 
     record.age = record.age_was # Rewrite new with old value 
    end 
    end 
end 

class Person 
    include ActiveModel::Validations 
    validates_with MyValidator 
end 

隨着ActiveModel::Dirty有沒有必要重新加載。

相關問題