开发者

Custom method after some validation passes

Ok.

1) I need to validate :link in my model and do that only if it is not blank (or nil).

2) If :link is not 开发者_运维问答blank and standard validation passes — I need to run my custom validation method to check URL availability.

By "standard" validation I mean something like this:

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 }

What is the correct way to implement this?


It checks for validation in your model only if link isn't blank:

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


Ok. With friends help I finally solved this.

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


validates_format_of :url_field, :with => URI::regexp(%w(http https))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜