[英]Devise, how to set auto redirection to a specific page if the user already logged in?
[英]Devise: How to create a new user being already logged in?
我將創建一個多用戶應用程序,因此,我將擁有一個有權創建新應用程序的管理員用戶。
我已經創建了UsersController
,但是當嘗試創建一個已經登錄的新用戶時,我正在重定向到 root_path,並顯示一條錯誤消息,顯示“您已經登錄”。
那么,我應該怎么做才能使這成為可能呢?
成立。
我剛剛從 devise 中刪除了可registerable
模塊,它就可以工作了。
在 controller 方法中,您不能只使用 go:
def create_user
@user = User.new(:email => params[:email], :password => params[:password])
@user.save
...
end
還有另一種解決方案。
您必須覆蓋注冊 controller 並從prepend_before_filter
中刪除操作(或操作)。
DeviseRegistrationController
源代碼在這里。
你可以看到:
prepend_before_filter :require_no_authentication, only: [:new, :create, :cancel]
它在創建方法之前跳轉到require_no_authentication
。 如果您想在登錄時創建新用戶,只需從數組中刪除:create
即可。
這就是我在 2015 年的做法
# in your terminal
rails g controller Registrations
注冊 controller 應該是這樣的,
# registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
skip_before_filter :require_no_authentication, only: [:new]
def new
super
end
end
重要的一行是skip_before_filter...
這將禁用沒有用戶登錄的要求。
controller 的路線如下所示,
# routes.rb
devise_for :users,
controllers: {:registrations => "registrations"}
這將告訴 devise 使用您的自定義注冊 controller
最后,為該操作設置自定義路由:
# routes.rb
as :user do
get "/register", to: "registrations#new", as: "register"
end
您可以覆蓋默認的 devise controller 並添加您的自定義邏輯,或者,創建一個新的(管理員)controller 並簡單地創建一個用戶可能會更容易。
@user = User.create!(:name => params[:foo], :email => params[:bar])
redirect_to @user
Devise 有大量關於如何自定義其行為的指南: https://github.com/plataformatec/devise/wiki/_pages
您可能對這個特別感興趣: https://github.com/plataformatec/devise/wiki/How-To:-Manage-Users-with-an-Admin-Role-(CanCan-method ) 但請確保看看rest的文章,有很多。
萬一有人仍在尋求幫助,因為這需要一段時間才能起作用,沒有明確的答案
在你的 controller
class UsersController < ApplicationController
def new
@user = User.new
end
def add_user
@user = User.new(user_params)
if @user.save!
redirect_to root_path
end
end
private
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end
在您的路線中:
get 'employees', to: 'users#new'
post 'employees', to: 'users#add_user'
最后是這樣的形式:
<%= form_for User.new , :url => {:action => "add_user"} do |user| %>
<%=user.email_field :email%>
<%=user.password_field :password%>
<%=user.password_field :password_confirmation%>
<%=user.submit 'add'%>
<%end%>
我在注冊 Controller 中添加:
class RegistrationsController < Devise::RegistrationsController
...
skip_before_action :require_no_authentication, only: [:new, :create]
...
end
它對我有用。 我現在可以 go 並創建一個新用戶。
@Mourkeer +1
對於 simple_form 4.2.0,采用 @Mourkeer 代碼並將route.rb
替換為:
# route.rb
devise_for :users, path_names: { registration: "registrations" }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.