我試圖在 Rails 中使 ruby?? 物件無效,但它不起作用。請看下面的代碼:
irb> user = User.first
irb> user.valid? # returns true
irb> user.errors[:base] << 'Making it Invalid'
irb> user.valid? # still returns true
那么user即使我向基礎添加了錯誤,物件如何仍然回傳有效。那么如何使我的用戶物件在 中無效irb?
uj5u.com熱心網友回復:
那么,即使我向基礎添加了錯誤,用戶物件如何仍然回傳有效?
這就是valid?幕后的作業(檔案)。
# Runs all the specified validations and returns true if no errors were
# added otherwise false .
def valid?(context = nil)
current_context, self.validation_context = validation_context, context
errors.clear
run_validations!
ensure
self.validation_context = current_context
end
正如您所看到的errors.clear,在觸發驗證之前就被呼叫,這就是它回傳的原因true
那么如何使我的用戶物件在 irb 中無效呢?
我可以使其無效的唯一方法是強制對其進行驗證的屬性無效。
user = User.last
user.valid? # => true
user.email = nil
user.valid? # => false
user.errors.messages # => {:email=>["can't be blank", "is invalid"]}
我從對另一個答案的評論中看到,這不是您需要/想要的,而是它的作業原理。
uj5u.com熱心網友回復:
我認為默認情況下,該valid?函式將為errors每次呼叫清除。所以你不能附加到它,你可以嘗試使一個或多個屬性無效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/376650.html
標籤:红宝石轨道
