确定。
1)我需要验证模型中的:link
,并且只有在它不是空白(或零)时才这样做。
2)如果:link
不为空且标准验证通过 - 我需要运行自定义验证方法来检查网址可用性。
按标准"验证我的意思是这样的:
validates :link, :presence => true, :uniqueness => true,
:format => { :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix }
实现此目的的正确方法是什么?
答案 0 :(得分:0)
仅当链接不为空时,它才会检查模型中的验证:
validates_presence_of :link, :uniqueness => true,
:format => { :with => /^(http|https)://[a-z0-9]+([-.]{1}[a-z0-9]+).[a-z]{2,5}(:[0-9]{1,5})?(/.)?$/ix }, :if => :link_present?
def link
self.link
end
def link_present?
link.present?
end
答案 1 :(得分:0)
validates_format_of :url_field, :with => URI::regexp(%w(http https))
答案 2 :(得分:0)
确定。在朋友的帮助下,我终于解决了这个问题。
class Post < ActiveRecord::Base
# skipped some things not necessary
validates_format_of :link, :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/ix , :allow_blank => true
validates_length_of :link, :maximum => 2000
validates_uniqueness_of :link, :allow_blank => true
validate :ensure_link_is_available, :if => proc{|post| post.link.present? && post.errors.empty?}
def ensure_link_is_available
begin
require "net/http"
url = URI.parse(self.link)
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)
rescue
# error occured, add error
self.errors.add(:link, 'The requested URL could not be retrieved')
else
# valid site
if (res.code.to_i > 308)
error_message = 'Server responded with ' + res.code
self.errors.add(:link, error_message)
end
end
end
end