javascript - 更新应用程序布局图标

标签 javascript ruby-on-rails ruby ajax

在我的应用程序 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/

相关文章:

ruby-on-rails - 带有 git remote 的 Gem 文件在 heroku push 上失败

ruby-on-rails - Rails 回合制游戏管理器

javascript - 使用 javascript 或 ruby​​ 分割此字符串

javascript - 为什么这个javascript效果不能在ie7上使用?

javascript - jQuery each 太快了

mysql - 在 Rails 中创建表和主键问题

sql - ActiveRecord 查找 - 跳过记录或获取每 N 个记录

javascript - 如何在不更改元素的子元素的情况下更改元素的文本?

javascript - 如何使用 Firebase/Node.js 遍历大型数据集?

ruby-on-rails - 是否可以将 globalize3 添加到外部 ActiveRecord 模型类?