在我的应用程序 Controller 中,我有一个方法用于在应用程序布局菜单上设置通知和通知图标。我使用 before_action 运行此方法:
def set_notifications
if user_signed_in?
@notifications = Notification.where(user_id: current_user.id)
@notifications.each do |n|
if n.read == false
return @icon_path = 'notification-alert-icon'
end
end
@icon_path = 'notification-icon'
end
end
这工作正常,因为当我有未读通知时,我会得到正确的通知图标:
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><%= image_tag(@icon_path) %></a>
<ul class="dropdown-menu">
<% if @notifications == 0 %>
<li class="text-center" style="color:white;">Você ainda não tem notificações</li>
<% else %>
<% @notifications.each do |n| %>
<li><%= link_to n.question.title, question_path(n.question), class: 'text-center' %></li>
<% end %>
<% end %>
<li role="separator" class="divider"></li>
<li><%= link_to 'Ver todas as notificações', "#" %></li>
</ul>
</li>
当用户单击通知图标,然后单击收到通知的问题时,questions_controller 会将该通知标记为已读(在显示操作内):
notifications = Notification.where(question_id: question.id) if Notification.exists?(question_id: question.id)
if notifications
notifications.each do |notification|
if notification.user_id == current_user.id
notification.read = true
notification.save
end
end
end
我无法做的是:在将通知标记为已读后,如何更新应用程序布局上的 @notifications 对象和通知图标?我知道我可以调用 set_notifications 方法,但仅此一点不会重新加载应用程序布局并更改图标,对吗?
最佳答案
您的 Controller 代码在 View 渲染之前运行完成,因此您可以在渲染阶段之前尽一切努力完成设置。在该阶段之前,您可以随意更改 @icon_path
等变量,最后设置的值就是使用的值。
如果您需要在 HTML 发送到浏览器后禁用 View 中的图标,则需要使用 JavaScript 将其关闭。
关于javascript - 更新应用程序布局图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36161829/