如何在rails中保存http引用
我正在尝试保存用户注册时来自的网站。现在我的 ApplicationController 中有一个 before_filter :
before_filter :save_referer
def save_referer
unless is_logged_in?
session['referer'] = request.env["HTTP_REFERER"] unless session['referer']
end
end
然后,当创建用户时,它会检查此会话变量并将其设置为 nil。有时这不起作用,我担心使用这样的会话可能会发生一些意想不到的事情。有人有更好的方法吗?或者也许有一些输入?
编辑:这是我用来保存引用者的逻辑:
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
有什么理由认为这不起作用?
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
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?
EDIT: 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
User
def save_with(referer)
self.referer = referer unless referer == "null"
self.save
end
Is there any reason why this should not work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为你的方法有一个缺陷。只要用户正在访问页面并且未登录,过滤器代码就会运行。因此,
session['referer']
不会为零的唯一方法是,他们直接进入注册页面,他们(大概)会在其中发布登录信息,然后您检查会话变量。我认为您可能只需要检查一次引荐来源网址 - 为此,您必须修改过滤器代码。
现在,当您想知道他们的引荐来源网址是什么时,它要么是有效的网址,要么是“无”。请注意,由于它位于会话中,因此并不完美:他们可以转到另一个 url 然后返回,会话仍然有效。
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.
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.
美丽的 ;-)
beautiful ;-)
乔纳森:使用会话时,答案有效。如果您不需要更好的信息,您还应该使用 cookie。用户可以通过链接(带有引荐来源网址)访问您的网站,然后离开一天并再次直接返回您的网站(现在没有引荐来源网址)。最好将信息也保存到以下样式的 cookie
还有一个 gem https://github.com/holli /referer_tracking 帮助自动处理这些和其他跟踪。
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
There is also a gem https://github.com/holli/referer_tracking to help handle these and other trackings automatically.