我正在使用这个库 ( https://github.com/CodeSeven/toastr ),我正在尝试将我的 Flash 通知推送到 Toastr 为我提供的 javascript 函数。如何为每个错误或通知调用此函数?
这是用于制作 toastr 通知的方法之一:
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 block 中使用此方法:
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/<your layout>.html.erb
# (or in a partial to be reused in various layouts)
# the <script> tag isn't needed if code snippet is
# included in an existing script block, of course.
<% if flash[:toastr] %>
<script type="text/javascript">
<% flash[:toastr].each do |type, message| %>
toastr.<%= type %>(<%= message.inspect %>)
<% end %>
</script>
<% end %>
因此,通过这种方式,您可以从 flash
对象中获得您习惯的所有标准行为,并且您可以轻松理解直接通过 erb 在 View 中编写的 javascript。当然,您可能需要向 ApplicationController#toast
方法添加一个选项散列,这样您就可以不时执行 flash.now[:toastr]
。等等......但这应该让你开始。
关于javascript - Rails 4 - Toaster 通知而不是 flash 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18604219/