How to manually create a new user and user session in Devise?

旧城冷巷雨未停 提交于 2019-11-29 20:45:25

You can create a new Devise user simply by creating a new user model (see https://github.com/plataformatec/devise/wiki/How-To:-Manage-users-through-a-CRUD-interface)

@user = User.new(:email => 'test@example.com', :password => 'password', :password_confirmation => 'password')
@user.save

To sign in your newly created user, use sign_in @user

Saving the newly created user before sign_in will fail because devise has not yet filled the required fields for User object yet. So David's code will work for the current page, but the next page won't get the signed in user, since the user is only saved after the session is set. This happens when I use Mongoid, and I don't know if it is a problem specific to Mongodb.

To address this problem, I have a very imperfect solution to call sign_in twice. The first sign_in will save the user. It just works but people can improve it certainly.

@user = User.new(:email => 'test@example.com',
                 :password => 'password',
                 :password_confirmation => 'password')
# This will save the user in db with fields for devise
sign_in @user
# :bypass is set to ignore devise related callbacks and only save the
# user into session.
sign_in @user, :bypass => true 
Raúl Contreras

For new people seeing this question...

A simple way to do this is in your

config/routes.rb

you should have a line like the following :

devise_for :users

so, you just have to add a path prefix that devise will use:

devise_for :users, :path_prefix =>'auth'

Hope it helps!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!