At times you need the user to check out your application without having to sign up. Play around with the features and if they are interested they can sign up. It’s easy to create a guest record on visit of the page, but the difficult part is in transferring the data from the guest to the signed up user.
Setup
Assuming you have a default devise setup on a user, you need to override the current_user
method devise provides out of the box.
First we’ll need to add a guest column to our user model.
1
|
|
1 2 3 4 5 |
|
Overwrite the CurrentUser Method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
Since we use the current_user
method in our application, we default to normal behaviour. If there’s none we create a guest_user. The logic is simple,
if the session[:guest_user_id]
is nil we create one otherwise we use that id itself.
The create_guest_user
method instantiates a user and within a block sets the guest attribute to true. The reason we do that is because guest is not accessible as an attribute and setting it normally would throw a mass assignment error.
You probably have some logic in the navigation bar when going to the homepage, hence the guest user record gets created whenever you make your first reference to current user.
Transferring data to signed up user.
Let’s say the user finds your application beneficial and decides to sign up. Here is the code needed to transfer the information.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
We want the new action to be the same, hence we call super
. However we are overriding the create action. After saving the user we call move to on the current_user
if they are a guest. move_to
is a method defined on the user model.
1 2 3 4 5 6 7 8 9 |
|
In this case we move all the todos to the user who has just signed up. Once that is done we sign_up the user using devise’s built in sign_up
method.
You might be thinking about deleting the guest user right now, but you should not in case you have relations dependent to it. You best bet would be to create a cron that deletes the guest user’s every 24 hours.
1 2 3 4 |
|
And there it is, guest users who can interact with your app.