2017-05-08 56 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 

请记住,没有不管你选择哪种场景,渲染/重定向应该添加到你的事务之外。