我想知道如果我的方法設置不正確,因爲我的驗證嘗試在該方法的中途被忽略。 (我提供了一個基本的例子,我想在添加更多之前得到這個工作)自定義表單驗證Rails
我有一個窗體屬於同一個對象的兩種變體。表格由列animal_type區別,你可以在我的方法看
class Animal < ActiveRecord::Base
before_save :animal_form_validation
private
def animal_form_validation
if self.animal_type == 'Dog'
ap('Im validating the dog Form')
if self.name.length <= 0
errors.add(:name, "Name cannot be blank")
end
elsif self.animal_type == 'Cat'
ap('Im validating the cat form')
if self.name.length <= 0
errors.add(:name, "Name cannot be blank")
end
end
end
end
我是否提交貓或狗我在控制檯中獲取正確的信息(使用真棒打印),因此該方法在運行和知道我要提交哪個表單,但是對於下一個if語句,它將被忽略。
所以我有我的語法錯誤?或者我在名稱字段上調用錯誤的驗證檢查?
感謝
我假設你的實際驗證更復雜,這就是爲什麼你不只是使用'validates_presence_of:name'? – pjmorse 2014-09-23 12:54:53
是的,當然:-)即將移動到其他地方之前,我正在測試一個字段的驗證 – Richlewis 2014-09-23 12:55:38
由於某種原因,'self.name.length <= 0'測試看起來很奇怪。如果你嘗試'self.name.blank?'它會起作用嗎? – pjmorse 2014-09-23 12:57:08