我在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