Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set 'current_user' even though a user is not logged in? - Rails 3

I am using Devise for authentication, and when someone visits a specific URL (with specific params in the URL), I would like to set the 'current_user' to a specific value from the db.

How do I do that ?

Also, will I have to make sure all the validation requirements are satisfied ? E.g., my user model has:

validates_presence_of :username, :email

If I set the current_user, would I have to set both the :username & :email, or can I just do one or the other ?

like image 587
marcamillion Avatar asked May 07 '11 22:05

marcamillion


2 Answers

You could try

@user = User.where(:x => "y").first # Find the user depending on the params
sign_in(@user)
# do work
sign_out(@user)

I don't know if that's the best way to do it, but it will set current_user.

like image 83
Fareesh Vijayarangam Avatar answered Sep 18 '22 06:09

Fareesh Vijayarangam


devise's current_user helper sets the instance variable @current_user, so doing this:

@current_user = User.first

will also set current_user to the selected user.

like image 44
handler Avatar answered Sep 22 '22 06:09

handler