✨
通知機能(既読、未読、検索)
はじめに
通知機能だけでは飽き足らず、未読と既読と検索全部つけちゃおうとする謎ムーブを
かましました。色々教わったんでまとめていきたいと思います。
実装
通知する機能は以前作ったのでそこに未読と既読を分けるために別のクラスをつけて色分けで判断しました
notifications.index.html.erb
<% notifications = @notifications.where.not(visitor_id: current_user.id) %>
<table class='table'>
<% notifications.each do |notification| %>
<tr class="<%= notification.is_checked ? "table_group2" : "table_group" %>">
<td>
<%= render "notification", notification: notification %>
</td>
</tr>
<% end %>
class="<%= notification.is_checked ? "table_group2" : "table_group" %>"は、既読されていたらtable_group2のクラスに
まだ既読されていなかったらtable_groupのクラスが付与されるように条件分岐しています。
application.css
.table_group {
background-color: #FFFFEE;
}
.table_group2 {
background-color: #FFFFEE;
opacity: 0.6
}
ここの色はお好みで既読しているものは薄く設定しました。
検索フォーム
イメージ

search-form.html.erb
<%= form_tag(notifications_path, method: :get) do %>
<%= select_tag(:range, options_for_select([['新しい順', 'latest'], ['古い順', 'oldest']], {selected: params[:range]})) %>
<%= select_tag(:option, options_for_select([['すべて', 'all'], ['未読', 'uncheck'], ['既読', 'checked']], {selected: params[:option]})) %>
<%= submit_tag '検索', name: nil %>
<% end %>
form_tagとは、railsで情報を送信するためのヘルパーメソッドです。
form_tagを使うことにより、簡単に入力フォームに必要なHTMLを作成することができます。
ここで既読未読を分けるように実装しました。
場合わけ
notifications_controller.erb
notices = current_user.passive_notifications
case params[:option]
when 'uncheck'
# 未読
@notifications = notices.where(is_checked: false)
when 'checked'
# 既読
@notifications = notices.where(is_checked: true)
else
# すべて
@notifications = notices
end
case params[:range]
when 'latest'
# 新しい順
@notifications = @notifications.order(created_at: :desc)
when 'oldest'
# 古い順
@notifications = @notifications.order(created_at: :asc)
else
# latest, oldest以外の文字列の場合
@notifications = notices.order(created_at: :desc)
end
(created_at: :desc)が新しく作られた順
(created_at: :asc)が古い順です
最後に
要点だけまとめました。不明な点はお気軽にコメントください。
Discussion