Reputation:
I am using toastr gem for my notifications. I am trying to add a toastr notification to my application whenever a method on my application_controller.rb
is active.
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def user_not_authorized
toastr.info('You cannot access this page.', 'info')
redirect_to contacts_path
end
As you can see I tried to add toastr
function on my controller, however this doesn't work. How can I show this toastr notification whenever this method hits or simply whenever a non-admin user access an unathorized page?
Upvotes: 0
Views: 880
Reputation: 14890
To build on the first answer, this is what I did in my app. Added what I wanted to show to flash
in the controller and then show the flash messages in toastr
I'm using the great slim
extension there, add it with gem 'slim-rails'
and save this file as _messages.html.slim
, you can then include it in your layout file.
- flash.each do |name, msg|
javascript:
window.onload = function() {
var name = "#{name}";
if (name == 'info' || name == 'notice') {
toastr.info("#{msg}");
}
else if (name == 'success') {
toastr.success("#{msg}");
}
else if (name == 'error') {
toastr.error("#{msg}");
}
else {
toastr.info("#{msg}");
}
};
Upvotes: 1
Reputation: 341
toastr
is a Javascript library and you can't use it within Ruby code.
However, if you want to show some kind of notifications to a user and define them in the context of a Rails controller, you can make use of Rails Flash Notifications.
In the application_controller.rb
file:
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
def user_not_authorized
flash[:notice] = "You cannot access this page."
redirect_to contacts_path
end
And somewhere in your HTML/ERB file, you would render the HTML elements for each one of the the flash notifications set in the controllers:
<html>
<!-- <head/> -->
<body>
<% flash.each do |name, msg| -%>
<%= content_tag :div, msg, class: name %>
<% end -%>
<!-- more content -->
</body>
</html>
You can consult more example of its usage in the link above.
Upvotes: 0