开发者

Rails Detect If User's Very First Visit

开发者 https://www.devze.com 2023-02-10 19:53 出处:网络
I\'m trying to make the user fill out a questionnaire if it is their first time visiting the site. My controllers are set up like this:

I'm trying to make the user fill out a questionnaire if it is their first time visiting the site.

My controllers are set up like this:

class MainController < BaseController
end

class BaseController < ApplicationController
  before_filter :first_time_visiting?
end

class ApplicationController &l开发者_高级运维t; ActionController::Base
  def first_time_visiting?
    if session[:first_time].nil?
      session[:first_time] = 1
      redirect_to questionnaire_path unless current_user
    end
  end
end

When I close the browser and re-open it though, I always get redirected to the questionnaire.


You have to set a cookie in the browser for that user in order to allow detection at a later time, i.e. after the user closes the browser. Setting and reading cookies in rails is easy. Checkout the documentation for some example usage. http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html


Stumbled on this question, my solution is just jQUery and involves setting localStorage (make sure you have a polyfill). Hide the element you want to only show once.

$(function() {
  if ( localStorage.getItem('visited') ) {
    return;
  }

  var $el = $('.only-show-on-first-visit');
  $el.slideDown(800);
  localStorage.setItem('visited', true);
  $el.find('.close').click(function() {
    $el.slideUp();
  });
});


// polyfill
if (!('localStorage' in window)) {
  window.localStorage = {
    _data       : {},
    setItem     : function(id, val) { return this._data[id] = String(val); },
    getItem     : function(id) { return this._data.hasOwnProperty(id) ? this._data[id] : undefined; },
    removeItem  : function(id) { return delete this._data[id]; },
    clear       : function() { return this._data = {}; }
  };
}


Add a 'last logged in time' field on your user table. When that is nil do foo and !nil do bar.

0

精彩评论

暂无评论...
验证码 换一张
取 消