currently I have a rails 3 app with devise. it requires the users to register / signin for access.
I would like to enable guest users. So that when a user visits certain views a guest user account is created for that user and then if/when they authenticate/register that guest user开发者_高级运维 is then upgraded to a normal user.
Think of the app as a chat room. I want guest users to be able to join the chat room, then later oauth into twitter to register. But I don't want to force users to register before joining.
Suggestions?
I found this: https://github.com/plataformatec/devise/wiki/How-To:-Create-a-guest-user
Problem with that is I added the helper, but don't understand how to initiate current_or_guest_user. Also not sure how to initiate per specific allowed views?
Any ideas? Pointers? Thanks
Another more transparent way is this:
def current_user
super || guest_user
end
private
def guest_user
User.find(session[:guest_user_id].nil? ? session[:guest_user_id] = create_guest_user.id : session[:guest_user_id])
end
def create_guest_user
u = User.create(:name => "guest", :email => "guest_#{Time.now.to_i}#{rand(99)}@example.com")
u.save(:validate => false)
u
end
After following the wiki, just replace calls to current_user
with current_or_guest_user
As far as views goes, do it in the controller with a before_filter.
Without seeing any code from you it is hard to guess, but in pseudo-code it would be something like
class ChatController < ApplicationController
before_filter authenticate_user!, :except => [:join] #this will force users to log in except for the join action
def join
chat_handle = current_or_guest_user.handle
# some more code...
end
Checkout this rails cast about guests users. Details about Devise at around 5:40.
精彩评论