【问题标题】:Rendering an action with :notice that depends on a URL param使用取决于 URL 参数的 :notice 呈现操作
【发布时间】:2012-06-27 04:34:57
【问题描述】:

我有一个动作“批准”,它呈现一个视图,该视图显示来自模型(类)的一些内容。在视图中,我有一个使用 URL 参数 (:id) 调用 accept 的 link_to。 accept 操作完成后(将批准设置为 true),我想再次呈现 approval 并显示一条消息(“已保存!”)。但是,与静态登录页面不同,批准操作在第一次调用时需要一个参数。第二次渲染时,会发生运行时错误(显然)。使用 Flash 通知致电 approval 的最佳方式是什么?

def approval
  @c = Class.find(params[:id])
end


def accept
  @c = Class.find(params[:id])
  @c.approve = true
  @c.save

  render 'approval', :notice => "Saved!"
end

【问题讨论】:

  • 第二次找不到@c id 导致运行时错误。所以你可以传递 id。

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

将此render 'approval', :notice => "Saved!" 更改为

flash[:notice] = "Saved!"
redirect_to :back

【讨论】:

  • :back - 返回发出请求的页面。对于从多个地方触发的表单很有用。 redirect_to(request.env["HTTP_REFERER"]) 的简写
【解决方案2】:

您可以使用FlashHash#now设置当前动作的通知

flash.now[:notice] = 'Saved !'
render 'approval'

http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html#method-i-now

【讨论】:

    【解决方案3】:

    摘自:http://www.perfectline.ee/blog/adding-flash-message-capability-to-your-render-calls-in-rails

    现在控制器中的常见模式如下所示:

    if @foo.save
      redirect_to foos_path, :notice => "Foo saved"
    else
      flash[:alert] = "Some errors occured"
      render :action => :new
    end
    

    我希望能够做到的是:

    if @foo.save
      redirect_to foos_path, :notice => "Foo saved"
    else
      render :action => :new, :alert => "Some errors occured"
    end
    

    添加这个功能实际上非常简单——我们只需要创建一些扩展渲染函数的代码。 下一段代码实际上扩展了包含重定向调用功能的模块。

    module ActionController
      module Flash
    
        def render(*args)
          options = args.last.is_a?(Hash) ? args.last : {}
    
          if alert = options.delete(:alert)
            flash[:alert] = alert
          end
    
          if notice = options.delete(:notice)
            flash[:notice] = notice
          end
    
          if other = options.delete(:flash)
            flash.update(other)
          end
    
          super(*args)
        end
    
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      • 1970-01-01
      • 2016-05-10
      • 2014-04-07
      • 2016-11-07
      • 1970-01-01
      • 2016-04-26
      相关资源
      最近更新 更多