0

I have a Ruby on Rails 5.2 app runnng on Ruby 2.6.6 and on the following route: /api/popups it gives me the 500 internal server error.

In the production log I see the following messages:

Started GET "/api/popups" for IP at 2020-12-30 11:12:30 +0000
INFO -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] Processing by controller2#index as HTML
INFO -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] Completed 500 Internal Server Error in 3ms (ActiveRecord: 0.0ms)
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69]   
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] NoMethodError (undefined method `host' for nil:NilClass):
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69]   
FATAL -- : [e7a305ff-9d4d-4c83-9572-9ea0708e8f69] app/controllers/concerns/controller1.rb:14:in `popups_for_domain'
[e7a305ff-9d4d-4c83-9572-9ea0708e8f69] app/controllers/controller2.rb:5:in `index'

The controller2.rb index (line 5) looks like:

def index
    popups = popups_for_domain.includes(:popup_template, :color_schema, :target_sets)
end

The controller1.rb line 14 contains:

def popups_for_domain
    return @popups_for_domain if @popups_for_domain
    referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i, '')
    @popups_for_domain = Popup.where(domain: referer_domain)
end

The error points to the host function from this line: referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i, '')

What is wrong there and how can I fix it? Thanks.

Pascut
  • 3,291
  • 6
  • 36
  • 64

2 Answers2

2

Addressabel::URI.parse returns nil when the URL parsed to it was nil or false. That means – at least sometimes – you do not have a request.referer and you need to handle those cases too.

Something like this might work for you:

def popups_for_domain
  return @popups_for_domain if @popups_for_domain
  return unless request.referer      

  referer_domain = Addressable::URI.parse(request.referer).host.gsub(/^w{3}\./i, '')
  @popups_for_domain = Popup.where(domain: referer_domain)

end

spickermann
  • 100,941
  • 9
  • 101
  • 131
0

According to: https://stackoverflow.com/a/6880668/1564840

request.referrer will/may be empty when the enduser:

- entered the site URL in browser address bar itself.
- visited the site by a browser-maintained bookmark.
- visited the site as first page in the window/tab.
- clicked a link in an external application.
- switched from a https URL to a http URL.
- switched from a https URL to a different https URL.
- has security software installed (antivirus/firewall/etc) which strips the referrer from all requests.
- is behind a proxy which strips the referrer from all requests.
- visited the site programmatically (like, curl) without setting the referrer header (searchbots!).

In my case, I called the API url directly in my browser and that's why the referrer was missing.

Pascut
  • 3,291
  • 6
  • 36
  • 64