9

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

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
4

3 回答 3

7

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

flash[:notice] = "Saved!"
redirect_to :back
于 2012-06-27T04:40:14.157 回答
3

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

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

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

于 2014-02-05T14:17:43.450 回答
2

摘自: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
于 2013-10-24T02:46:37.060 回答