#393 Guest User Record
Nov 21, 2012 | 9 minutes | Authentication
Instead of presenting a sign up form to the user, consider creating a temporary guest record so the user can try out the application without filling in their information up front. They can then become a permanent member afterwards.
- Download:
- source code Project Files in Zip (71.5 KB)
- mp4 Full Size H.264 Video (19.9 MB)
- m4v Smaller H.264 Video (10.3 MB)
- webm Full Size VP8 Video (11.7 MB)
- ogv Full Size Theora Video (23.1 MB)
Browse_code
Browse Source Code
Resources
terminal
rails g migration add_guest_to_users guest:boolean rake db:migrate
index.html.erb
<p><%= button_to "Try it for free!", users_path, method: :post %></p>
layouts/application.html.erb
Logged in as <strong><%= current_user.name %></strong>. <% if current_user.guest? %> <%= link_to "Become a member", signup_path %> <% else %> <%= link_to "Log Out", logout_path %> <% end %>
user_controller.rb
def create @user = params[:user] ? User.new(params[:user]) : User.new_guest if @user.save current_user.move_to(@user) if current_user && current_user.guest? session[:user_id] = @user.id redirect_to root_url else render "new" end end
models/user.rb
class User < ActiveRecord::Base has_many :tasks, dependent: :destroy attr_accessible :username, :email, :password, :password_confirmation validates_presence_of :username, :email, :password_digest, unless: :guest? validates_uniqueness_of :username, allow_blank: true validates_confirmation_of :password # override has_secure_password to customize validation until Rails 4. require 'bcrypt' attr_reader :password include ActiveModel::SecurePassword::InstanceMethodsOnActivation def self.new_guest new { |u| u.guest = true } end def name guest ? "Guest" : username end def move_to(user) tasks.update_all(user_id: user.id) end end
lib/tasks/guests.rake
namespace :guests do desc "Remove guest accounts more than a week old." task :cleanup => :environment do User.where(guest: true).where("created_at < ?", 1.week.ago).destroy_all end end
loading