2014-11-08 42 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有没有必要重新加载。

相关问题