前提・実現したいこと
プログラミングスクールに通うプログラミング初心者です。
現在、ruby on rails でDM(1対1のチャット機能)アプリを開発しています。
現在、このDMアプリに通知機能を追加しているのですがそこで出たエラーを解決することができません。
今回は、DMをしたらDMをされた人に通知がいくようなシステムを作りたいと考えています。
(通知機能のindexページにアクセスしたところでエラー)
また、こちらのリンクをほとんど同じように参考にさせていただきました。
DM通知機能の参考
発生している問題・エラーメッセージ
NoMethodError in Notifications#index Showing dm_app/app/views/notifications/index.html.erb where line #4 raised: undefined method `visitor' for #<Notification::ActiveRecord_AssociationRelation:0x00007fd2fbfc10b8> Extracted source (around line #4): <% if notifications.exists? %> <% visitor = notifications.visitor %> #ここでエラー <% visited = notifications.visited %> <div> <%= link_to user_path(visitor) do %>
該当のソースコード
(notifications_controller.rb)
def index @notifications = current_user.passive_notifications end
通知機能ののマイグレーションファイルです。
class CreateNotifications < ActiveRecord::Migration[6.0] def change create_table :notifications do |t| t.integer :visitor_id t.integer :visited_id t.integer :room_id t.integer :message_id t.string :action t.boolean :checked t.timestamps end end end
(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)メッセージのモデル
has_many :notifications, dependent: :destroy
(room.rb)チャットルームのモデルです。
has_many :notifications, dependent: :destroy
notification.rb通知機能のモデルです。
class Notification < ApplicationRecord 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 end
(notifications/index.html.erb)通知機能のトップページ
<% notifications = @notifications.where.not(visitor_id: current_user.id) %> <% if notifications.exists? %> <% visitor = notifications.visitor %> <% visited = notifications.visited %> <div> <%= link_to user_path(visitor) do %> <%= visitor.name %>さんが <% end %> <% if notifications.action=='dm' %> あなたにDMを送りました <% end %> </div> <% else %> <p>通知はございません</p> <% end %>
補足
エラーメッセージでvisitorが定義されてないとありますが、参考資料では特に定義していなかったので自分も定義しませんでした。
なぜこのエラーが出てしまうのでしょうか、、?
アドバイスいただけますと幸いです。よろしくお願いいたします。
あなたの回答
tips
プレビュー