Skip to content

Instantly share code, notes, and snippets.

@zacstewart
Created October 2, 2012 17:35
Show Gist options
  • Save zacstewart/3821473 to your computer and use it in GitHub Desktop.
Save zacstewart/3821473 to your computer and use it in GitHub Desktop.
Rails Soft Sign-Up
class AnonymousUser < User
attr_accessible *ACCESSIBLE_ATTRS, :type, :token, as: :registrant
def register(params)
params = params.merge(type: 'User', token: nil)
self.update_attributes(params, as: :registrant)
end
end
class ApplicationController < ActionController::Base
protect_from_forgery
def authenticate_user!(*args)
current_user.present? || super(*args)
end
def current_user
super || AnonymousUser.find_or_initialize_by_token(anonymous_user_token).tap do |user|
user.save(validate: false) if user.new_record?
end
end
private
def anonymous_user_token
session[:user_token] ||= SecureRandom.hex(8)
end
end
class RegistrationsController < Devise::RegistrationsController
def create
@user = AnonymousUser.find(current_user.id)
if @user.register(params[:user])
sign_in_and_redirect @user.becomes(User)
else
render :new
end
end
end
RetrospectionApp::Application.routes.draw do
devise_for :users, controllers: {registrations: 'registrations'}
resources :posts, path: '/'
root to: 'posts#index'
end
@bsodmike
Copy link

I take it the User class is like:

class User < ActiveRecord::Base
  ACCESSIBLE_ATTRS = [:name, :email, ...]
  attr_accessible *ACCESSIBLE_ATTRS
end

?

Great post, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment