前提・実現したいこと
プログラミングスクールに通うプログラミング初心者です。
現在、ruby on rails でコメント通知機能を作成しています。
今回は困っていることとしまして、通知トップページ(notifications/index.html.erb)に①新規のコメントがあった場合は新規コメントがあります。②ない場合、もしくは全て既読済みの場合は新規コメントはありませんと表示したいのですが、②の条件式の記述方法で悩んでいます。
発生している問題・エラーメッセージ
新規コメントがある場合とない場合で条件式を作成したい。
該当のソースコード
(notification.rb)
default_scope -> { order(created_at: :desc) } belongs_to :room, optional: true belongs_to :message, optional: true belongs_to :visitor, class_name: 'User', foreign_key: 'visitor_id', optional: true belongs_to :visited, class_name: 'User', foreign_key: 'visited_id', optional: true
通知機能ののマイグレーションファイルです。
(user.rb)
has_many :active_notifications, class_name: 'Notification', foreign_key: 'visitor_id', dependent: :destroy has_many :passive_notifications, class_name: 'Notification', foreign_key: 'visited_id', dependent: :destroy
(message.rb)
class Message < ApplicationRecord belongs_to :user belongs_to :room has_many :notifications, dependent: :destroy end
(notifications_controller.rb)
def index @notifications = current_user.passive_notifications end def update notification=Notification.find(params[:id]) if notification.update(checked: true) redirect_to action: :index end end
(notifications.index.html.erb)通知ページ
<% notifications = @notifications.where.not(visitor_id: current_user.id) %> <% if notifications.exists? %> <%= render @notifications %> <% else %> <p>通知はございません</p> <% end %>
補足
新規コメントがない(false)の場合もしくはcheckedカラムが、0の場合には表示させないとすることで
できそうと考えましたが、その記述方法がわかりませんでした。ご教授いただけないでしょうか?
あなたの回答
tips
プレビュー