I'm trying to write a simple validation to check if a user's domain name is valid. Here's the model:
class User < ActiveRecord::Base
require 'net/http'
validate :domain_check
def domain_check
uri = URI(domain)
request = Net::HTTP.new uri.host
response = request.request_head uri.path
if response.code.to_i > 400
errors.add(:domain, "This doesn't appear to be an valid site.")
end
end
end
This is based off the example in the Rails how to here.
However this keeps throwing an error bad argument (expected URI object or URI string)
about the line
uri = URI(domain)
I assume the domain
variable is not getting to the function-- it seemed odd in the example in the Rails book that it didn't pass any variable, but the form vars are getting passed in correctly (I can see them in the debug info) and the form item domain
is populated.
How do I pass in the domain
var correctly so this custom validation method will work?
You can change the function to
class User < ActiveRecord::Base
require 'net/http'
validate :domain_check
def domain_check
uri = URI(domain)
request = Net::HTTP.get_response uri
if request.code.to_i > 400
errors.add(:domain, "This doesn't appear to be an valid site.")
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With