2013-12-15 82 views
0

我有一個Rails 3.2應用程序使用Devise進行身份驗證。目前,new_user_registration工作正常,並且edit_user_registration路徑都按設計工作。不過,我設計了一個標籤式的用戶配置文件,其中用戶將有機會獲得各種形式(編輯註冊,網站設置等)從用戶編輯#show view

的問題

雖然users#show頁包含的部分,在拉表單來編輯註冊,但它實際上並不允許用戶進行編輯。我只是在用戶控制器中重新創建一個edit動作,但我想保留一些Devise的內置功能(例如丟失密碼等,不知道這是否有效)。

有沒有什麼辦法可以讓我編輯registrations#edit動作users#show視圖?

回答

1

你可以重寫Devise的默認行爲來使其工作。通過將您的show行動統一到設計RegistrationsController,然後宣佈的行動路線開始:

# app/controllers/users/registrations_controller.rb 
class Users::RegistrationsController < Devise::RegistrationsController 
    def show 
    end  
end 

# config/routes.rb 
devise_for :users, :controllers => { :registrations => "registrations" } 
devise_scope :user do 
    get "users/show"=> "users/registrations#show", :as => "show_registration" 
end 

然後,在你RegistrationsController#show行動,創建resource一個實例來傳遞給視圖:

# app/controllers/users/registrations_controller.rb 
class Users::RegistrationsController < Devise::RegistrationsController 
    def show 
     self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key) 
    end 

最後,向您的show.html.erb視圖添加一個表單,該表單將提交至RegistrationsController#update操作。您可以直接從default Devise registration/edit.html.erb template複製此:

<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { :method => :put }) do |f| %> 
    <%= devise_error_messages! %> 

    <div><%= f.label :email %><br /> 
    <%= f.email_field :email, :autofocus => true %></div> 

    <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> 
    <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div> 
    <% end %> 

    <div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br /> 
    <%= f.password_field :password, :autocomplete => "off" %></div> 

    <div><%= f.label :password_confirmation %><br /> 
    <%= f.password_field :password_confirmation %></div> 

    <div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br /> 
    <%= f.password_field :current_password %></div> 

    <div><%= f.submit "Update" %></div> 
<% end %> 
end 

瞧!您的自定義show操作將包含一個表單,該表單將當前註冊資源提交給默認Devise RegistrationsController#update操作。

+0

謝謝,現在就試試這個。 – miler350

+0

當然,請告知它是否有效...我自己並沒有實際執行它。 – zeantsoi

+0

工作就像一個魅力。 – miler350