Scalahansolo
Scalahansolo

Reputation: 3065

Rails validations with parameters

In my code below, I am trying to call url_exist? as a validation for the website, but I am unsure of how to call url_exist? with the value of website. This seems like a silly question, but I can not figure it out.

Model

validates :website, presence: true, if: :url_exist?
...
def url_exist?(url_string)
  url = URI.parse(url_string)
  puts url
  binding.pry
  req.use_ssl = (url.scheme == 'https')
  req = Net::HTTP.new(url.host, url.port)
  path = url.path if url.path.present?
  req.request_head(path || '/')
  res.code != "404" # false if returns 404 - not found
rescue Errno::ENOENT
  false # false if can't find the server
end

Upvotes: 0

Views: 89

Answers (1)

Joe Kennedy
Joe Kennedy

Reputation: 9443

You already know the value of website because it's one of the object's attributes. So, just reference it in your url_exist? function.

validates :website, presence: true, if: :url_exist?

# ...

def url_exist?
  url = URI.parse(self.website)
  puts url
  # ...
end

I should also note that it seems like you're missing some code towards the end of the snippet you posted, so right now your url_exist? function will always return false.

Upvotes: 1

Related Questions