###前提・実現したいこと
rails4 ローカル環境。
現在Pusherを使用し通知機能を実装しました。
通知機能自体は無事実装することができました。
teratailでいうと、ヘッダーのベルマークにお知らせのカウントが表示されるようにはできました。
そして、通知されたものを一覧ページで表示させたいと思ったのですが、一覧ページでのデータの取得方法が分かりません。
受け取るお知らせは「トピック」「タイムライン」の2つあり、どちらもNotification
モデルとアソシエーションしてあります。
現在記述しているコードはこちらです。
notifications_controller.rb
def index # 自分の通知のみ取得、通知は新しい順に並び替える。 @notifications = Notification.where(user_id: current_user.id).order(created_at: :desc) end
notifications/index.html.erb
html
1<h2>お知らせ</h2> 2 <% @notifications.each do |notification| %> 3 <p> 4 <%= notification.comment.user.try(:name) %>さんが 5 あなたの投稿(<%= link_to "#{notification.comment.topic.title}", topic_path(notification.comment.topic, notification_id: notification.id) %>)にコメントしました。 6 </p> 7 <p> 8 <%= notification.commenttl.user.try(:name) %>さんが 9 あなたの投稿(<%= link_to "#{notification.commenttl.timeline.content}", timeline_path(notification.commenttl.timeline, notification_id: notification.id) %>)にコメントしました。 10 </p> 11 <% end %>
###発生している問題・エラーメッセージ
現在のnotifications/index.html.erb
での記述では
ActionView::Template::Error (undefined method `user' for nil:NilClass):
とエラーになってしまいます。
トピックとタイムラインどちらかだけのデータなら取得して表示はできるのですが、どちらのお知らせも表示する方法が分かりません。
こういう場合はそもそもeachメソッドではなく違うメソッドを使ったりするのでしょうか?
説明が分かりづらい点もあるかとは思いますが、ご教授のほどよろしくお願いします。
###補足
notificationsテーブル
create_table "notifications", force: :cascade do |t| t.boolean "read", default: false t.integer "user_id" t.integer "comment_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "commenttl_id" end add_index "notifications", ["comment_id"], name: "index_notifications_on_comment_id", using: :btree add_index "notifications", ["commenttl_id"], name: "index_notifications_on_commenttl_id", using: :btree add_index "notifications", ["user_id"], name: "index_notifications_on_user_id", using: :btree
下記のようにトピック、あるいはタイムラインのみを取得すると、どちらかのデータは正常に表示はできます。
下記の場合はトピックに関するお知らせのみ表示されます。
notifications/index.html.erb
html
1<h2>お知らせ</h2> 2 <% @notifications.each do |notification| %> 3 <p> 4 <%= notification.comment.user.try(:name) %>さんが 5 あなたの投稿(<%= link_to "#{notification.comment.topic.title}", topic_path(notification.comment.topic, notification_id: notification.id) %>)にコメントしました。 6 </p> 7 <% end %>
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/03/14 06:11
2017/03/14 06:34 編集
2017/03/14 06:39