Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Detect If User's Very First Visit

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 < 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.

like image 902
Dex Avatar asked Feb 14 '11 02:02

Dex


2 Answers

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

like image 73
Peer Allan Avatar answered Nov 07 '22 10:11

Peer Allan


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 = {}; }
  };
}
like image 37
muffs Avatar answered Nov 07 '22 11:11

muffs