0

How can I get this to work? Use !!URI.parse(url) or self.url ?

class Idea < ActiveRecord::Base
  attr_accessible :body, :url
  validates :body, presence: true, :length => { :in => 6..240 }
  validates :body, uniqueness: true
  validates :url, presence: true
  validate :good_url
  require 'uri'
  def good_url
    errors.add(:url, 'not valid') unless URI.parse(url)
  end
end
  • Here is a question addressing the same issue http://stackoverflow.com/questions/7167895/whats-a-good-way-to-validate-links-urls-in-rails-3 – Ismael Abreu Oct 03 '12 at 23:31
  • [An updated UriValidator](http://stackoverflow.com/a/19423623/356895) – JJD Oct 17 '13 at 12:08

1 Answers1

1

If you just want to get it working, then how about:

errors.add(:url, 'not valid') if (url =~ URI::regexp).nil?

But if parsing urls is important to you, you might want to consider an alternative to ruby's standard URI implementation such as addressable, which handles UTF-8 characters, normalization and other edge cases that might be important depending on the context.

See also this: check if url is valid ruby

Community
  • 1
  • 1
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82