Rails 4 custom inspection method

I am trying to write a simple check to check if the domain name of the user is valid. Here is 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

Rails is based on an example here .

However, this continues to cause bad argument (expected URI object or URI string)a row error

uri = URI(domain)

I assume that the variable domaindoes not fall into the function - in the example in the Rails book, it seemed strange that it did not pass any variable, but the vars forms are transmitted correctly (I see them in the debugging information) and the form element is filled domain.

How to pass in domainvar correctly so that this custom validation method works?

+4
2
+1

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
+8

Source: https://habr.com/ru/post/1535836/


All Articles