我希望在rails中保存/更新模型時能夠用警告替換字段錯誤。基本上我想只寫周圍會產生錯誤的驗證方法的包裝,保存模型,也許在警告散列可(工作就像錯誤哈希):ActiveRecord - 用警告替換模型驗證錯誤
class Person < ActiveRecord::Base
# normal validation
validates_presence_of :name
# validation with warning
validates_numericality_of :age,
:only_integer => true,
:warning => true # <-- only warn
end
>>> p = Person.new(:name => 'john', :age => 2.2)
>>> p.save
=> true # <-- able to save to db
>>> p.warnings.map { |field, message| "#{field} - #{message}" }
["age - is not a number"] # <-- have access to warning content
任何想法如何我可以實現這個?我能夠將:warning => false
默認值添加到ActiveRecord::Validations::ClassMethods::DEFAULT_VALIDATION_OPTIONS
通過擴展模塊,但我正在尋找一些關於如何實現其餘部分的見解。謝謝。
非常酷,非常感謝! – sa125 2011-02-20 12:06:13
寶石版本0.5.1與rails 3兼容,但對gemspec的簡單更改(請參閱https://github.com/ivalkeen/validation_scopes/commit/acc1545a028605997e87fd41efece0ddffd3b999)允許它在rails 4中使用。 – KenB 2014-07-30 21:42:14