2017-05-08 47 views
0

我想提出一個錯誤,然後渲染註冊控制器的編輯頁面。但是當我遇到錯誤頁面凍結,我得到這個錯誤。沒有發現RegistrationsController的模板#更新

No template found for RegistrationsController#update rendering head :no_content 
Completed 204 No Content in 698ms (ActiveRecord: 2.3ms) 

這裏是我的控制器操作

def update 
    resource.transaction do 
     super do |user| 
     if membership_params.present? 
      ToggleAlertEmails.perform(user: current_user, params: membership_params) 
     end 

     if user.errors[:current_password].present? 
      raise ActiveRecord::Rollback 
      redirect_to edit_user_registrations_path 
     end 
     end 
    end 
    end 

當我打的raise ActiveRecord:Rollback它實際上回滾的變化就像我想,但它並沒有繼續和呈現編輯頁面。我怎樣才能做到這一點?

+0

您可能想從堆棧溢出中引用此答案,但請務必閱讀該問題,情況與您的情況類似。 [http://stackoverflow.com/questions/38460895/possible-to-render-and-raise-exception-in-rails-controller] – kparekh01

回答

0

移動redirect_to edit_user_registrations_path的事務之外,使用標誌(error在下面的例子)來執行回滾時只能重定向,像這樣:

def update 
    error = false 

    resource.transaction do 
    super do |user| 
     if membership_params.present? 
     ToggleAlertEmails.perform(user: current_user, params: membership_params) 
     end 

     if user.errors[:current_password].present? 
     error = true 
     raise ActiveRecord::Rollback 
     end 
    end 
    end 

    redirect_to edit_user_registrations_path if error 
end 

或者,如果你願意的話,避免國旗和再次使用user.errors[:current_password].present?

redirect_to edit_user_registrations_path if user.errors[:current_password].present? 

儘管您發佈的特定錯誤是因爲沒有爲update動作(例如update.html.erb)沒有意見,所以你需要創建一個或指定另一個渲染/重定向通過render/redirect_to

如果你想重定向到edit始終,則避免了最終if並保持redirect_to只:

redirect_to edit_user_registrations_path 

如果你想重定向到另一個動作或呈現不同的視圖(即,既不update也不edit)時,有沒有回退,使用完整的if/else聲明:

if user.errors[:current_password].present? 
    redirect_to edit_user_registrations_path 
else 
    redirect_to other_action_path 
end 

請記住,沒有不管你選擇哪種場景,渲染/重定向應該添加到你的事務之外。