如何在rails中保存http引用 [英] How to save http referer in rails

查看:56
本文介绍了如何在rails中保存http引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存用户注册时所在的站点.现在我的 ApplicationController 中有一个 before_filter:

I'm trying to save the site that a user came from when they sign up. Right now I have a before_filter in my ApplicationController:

before_filter :save_referer

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

然后在创建用户时,它会检查此会话变量并将其设置为 nil.有时这不起作用,我担心使用这样的会话可能会发生一些意外的事情.有没有人有更好的方法?或者一些输入?

Then when a user is created, it checks this session variable and sets it to nil. Sometimes this does not work and I'm worried there might be some unintended things happening with using session like this. Does anyone have a better way? Or some input perhaps?

这是我用来保存引用者的逻辑:

This is the logic I am using to save the referer:

def create     
    @user = User.new(params[:user])  
    if @user.save_with(session[:referer])
    ....
end

用户

def save_with(referer)
    self.referer = referer unless referer == "null"
    self.save   
end

有什么理由不这样做吗?

Is there any reason why this should not work?

推荐答案

我认为您的方法存在缺陷.只要用户点击页面并且未登录,过滤器代码就会运行.所以session['referer']为零的唯一方法是,如果他们直接进入注册页面,在那里他们(大概)发布他们的登录信息,然后你检查会话变量

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

现在,当您想知道他们的引用者是什么时,它要么是有效的 url,要么是无".请注意,由于它在会话中,因此并不完美:他们可以转到另一个 url 并返回,会话仍然有效.

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.

这篇关于如何在rails中保存http引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆