Rails 4 – Toaster通知而不是Flash通知

我正在使用这个库,( https://github.com/CodeSeven/toastr ),我正在尝试将我的Flash通知推送到Toastr为我提供的javascript函数。 如何针对每个错误或通知调用此函数?

这是用于制作烤面包机通知的方法之一:

toastr.warning('This is a warning!') 

我尝试在ApplicationController中创建一个方法,看看我是否可以在CanCan的默认错误上调用该方法。 我有各种版本的方法,但都没有。

 def toast(type, text) #if Logic here for various errors/notifications respond_to do |format| format.js { render action: "toastr.warning(#{text})", layout: false} end end def toast(type, text) #if Logic here for various errors/notifications "toastr.warning(#{text})" end 

然后我尝试在CanCan块中使用此方法:

 rescue_from CanCan::AccessDenied do |exception| toast :error, exception.message redirect_to root_url end 

我认为这是可能的,但我只是不确定如何实现它。 没有多少尝试这样做,可能有一个原因。 我愿意接受有关如何做我想做的事的任何建议。

这是一个实现Toast通知的测试应用程序: http : //codeseven.github.io/toastr/demo.html

我建议的是为这种东西制作一个新的flash类型,然后在你的布局中将它渲染为JS。

 ApplicationController def toast(type, text) flash[:toastr] = { type => text } end app/views/layouts/.html.erb # (or in a partial to be reused in various layouts) # the  <% end %> 

因此,通过这种方式,您可以从flash对象中获得您习惯的所有标准行为,并且您可以直接通过erb轻松理解在您的视图中编写的javascript。 您可能需要向ApplicationController#toast方法添加一个选项哈希,这样您flash.now[:toastr]可以执行flash.now[:toastr] 。 等等...但这应该让你开始。