即使用户未登录,如何设置'current_user'? - Rails 3

mar*_*ion 15 devise ruby-on-rails-3

我正在使用Devise进行身份验证,当有人访问特定的URL(URL中有特定的params)时,我想将"current_user"设置为db中的特定值.

我怎么做 ?

另外,我是否必须确保满足所有验证要求?例如,我的用户模型有:

validates_presence_of :username, :email
Run Code Online (Sandbox Code Playgroud)

如果我设置current_user,我是否必须同时设置:username&:email,或者我可以只做一个或另一个?

Far*_*gam 22

你可以试试

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

我不知道这是否是最好的方法,但它会设置current_user.


han*_*ler 5

current_userdevise 的帮助程序设置实例变量@current_user,因此执行以下操作:

@current_user = User.first
Run Code Online (Sandbox Code Playgroud)

还将current_user设置为所选用户。