How to save http referer in rails

…衆ロ難τιáo~ 提交于 2019-11-28 19:34:34

I think there's a flaw in your approach. As long as the user is hitting pages and is not logged in, the filter code will run. So the only way session['referer'] will not be nil is if they go straight to the signup page where they (presumably) post their login info and you check the session var.

I think you probably need to only check the referer once - to do this you'll have to modify your filter code.

def save_referer
  unless is_logged_in?
    unless session['referer']
      session['referer'] = request.env["HTTP_REFERER"] || 'none'
    end
  end
end

Now when you want to know what their referer is, it will either be a valid url or 'none'. Note that since it's in the session, it's not perfect: they could go to another url and come back and the session will still be valid.

def save_referer
  session['referer'] = request.env["HTTP_REFERER"] || 'none' unless session['referer'] && !is_logged_in?
end

beautiful ;-)

Jonathan:s answer works when using sessions. In case you wan't better information you should also use cookies. User can visit your site from a link (with a referer) then go away for a day and return directly to your site again (now without a referer). Would be better to save information also to a cookie in following style

def save_referer
  if cookies[:referer].blank?
    cookies.permanent[:referer] = request.env["HTTP_REFERER"] || 'none'
  end
end

There is also a gem https://github.com/holli/referer_tracking to help handle these and other trackings automatically.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!