我在Rails 4應用程序中使用自定義驗證。它只是一個用戶表單,應該提交用戶的域名,然後進行驗證以確保該網站存在。rails 4驗證問題
的驗證是這樣的:
validates :first_name, :last_name, :domain, presence: true
validate :domain_check
如果域留空,而不是從第一presence
驗證返回驗證錯誤,它運行:domain_check
功能。它似乎應該在第一次驗證失敗時立即返回?
第二,當它執行:domain_check
功能,我不知道如何來檢查domain
value--現在我這樣做:
def domain_check
Rails.logger.debug '###############'
Rails.logger.debug domain.inspect # prints ""
Rails.logger.debug domain # prints nothing
Rails.logger.debug domain.nil? # prints nothing
Rails.logger.debug '###############'
if domain.nil?
errors.add(:domain, "Domain is required.")
return
end
if domain.strip.starts_with?('http://')
domain.gsub 'http://', ''
elsif domain.strip.starts_with?('https://')
domain.gsub 'https://', ''
end
uri = 'http://'+domain
response = open(uri).read
# more stuff here
提交的表單上
uri = 'http://'+domain
返回
undefined method "+" for nil:NilClass
一行。我不明白這一點,因爲我試圖創建uri
字符串之前檢查domain
的值是否爲零。
這是在Ruby 2.0.0下運行 - 我相信這段代碼在Ruby 1.9.3下正常工作 - 是這樣的原因嗎?還是我錯過了明顯的東西?
謝謝!
什麼'Rails.logger.debug domain.class'打印? –
@ UriAgassi--'Rails.logger.debug domain.class'打印'String' – user101289