【问题标题】:Render the action that initiated update渲染启动更新的动作
【发布时间】:2011-03-06 00:39:07
【问题描述】:

我有一个 SettingsController,其中包含操作 accountprofile,还有一个 update,如下所示:

  def update
    @player = current_user
    if @player.update_attributes(params[:player])
      flash[:success] = "Profile updated."
      redirect_to :back
    else
      @title = "Edit"
      render
    end
end

现在配置文件和帐户操作都有一个对应的视图,并带有一个表单来编辑 Player 模型的一些记录。

当您尝试保存其中一种表单时,它失败了,即。它没有通过验证,它应该再次渲染初始化更新的操作,这样它才能显示适当的错误消息。

但问题是,我如何知道两者中的哪一个请求了更新,并渲染了正确的?基本上某种等效的 redirect_to :back 是我在这里寻找的。​​p>

【问题讨论】:

    标签: ruby-on-rails render


    【解决方案1】:

    这很难看,但有效:)

    render Rails.application.routes.recognize_path(request.referer)[:action]
    

    【讨论】:

    • ...我想这是一种恭维:)
    • 你说得对,这太丑了..!但如果它有效……你知道自 2011 年以来是否有任何新的东西出现?谢谢!!!
    • 它不能跨控制器工作。我有一个仪表板administration#dashboard,其视图是administration/dashboard.html.erb,它允许管理员通过employees#update 更新员工,使用你的方法,我有一个缺少模板错误,因为仪表板在子文件夹/administration/ 中,而rails 只是在里面看//employees/
    • 啊实际上Rails.application.routes.recognize_path(request.referer)返回了:controller:action的哈希,所以你可以通过/将两者结合起来解决文件夹问题。 render Rails.application.routes.recognize_path(request.referer).map{ |k,v| v }.join('/')
    • 它在 2022 年仍然有效!不确定是否有更漂亮的方法?
    【解决方案2】:

    通常您可以通过应用模式来解决此问题:

    def edit
      @title = "Edit"
    
      # ...
    end
    
    def update
      # Update using the exception-generating variant
      @player.update_attributes!(params[:player])
    
      # ... More actions if successful
    
    rescue ActiveRecord::RecordInvalid
      self.edit
      render(:action => 'edit')
    end
    

    这通常通过为您处理模型实例的加载的before_filter 来简化。

    由于这可以大量使用,有时您可以将其包装到委托方法中:

    def fallback_render(action)
      send(action)
      render(:action => action)
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 1970-01-01
      • 2014-06-07
      • 2020-08-24
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      相关资源
      最近更新 更多