###前提・実現したいこと
rails4ローカル環境。
現在Pusherを使用した通知機能の実装をしております。
実現したいことは、トピック(topic)とタイムライン(timeline)に投稿された記事にコメントがされた際に通知されるというものです。
トピック機能とタイムライン機能は別々に存在しております。
今回通知機能を実装したやり方は、
まず、通知機能となるNotificationモデルを作成しました。
そしてアソシエーションの設定。
notification.rb
belongs_to :user belongs_to :comment belongs_to :commenttl
commenttl.rb
[タイムライン機能のコメント]
belongs_to :user belongs_to :timeline has_many :notifications, dependent: :destroy
comment.rb
[トピック機能のコメント]
belongs_to :user belongs_to :topic has_many :notifications, dependent: :destroy
コントローラーの記述はこのようにしました。
見やすいように不要と思われる部分は省略して記載します。
notifications_controller.rb
def index # 自分の通知のみ取得、通知は新しい順に並び替える。 @notifications = Notification.where(user_id: current_user.id).order(created_at: :desc) end
commenttls_controller.rb
def create @commenttl = current_user.commenttls.build(commenttl_params) @timeline = @commenttl.timeline @notification = @commenttl.notifications.build(user_id: @timeline.user.id ) # クライアント要求に応じてフォーマットを変更 respond_to do |format| if @commenttl.save format.html { redirect_to timeline_path(@timeline), notice: 'コメントを投稿しました。' } format.json { render :show, status: :created, location: @commenttl } # JS形式でレスポンスを返します。 format.js { render :index } # pusherを使って通知件数をリアルタイムで更新させる Pusher.trigger("user_#{@commenttl.timeline.user_id}_channel", 'notification_created', { unread_counts: Notification.where(user_id: @commenttl.timeline.user.id, read: false).count }) else format.html { render :new } format.json { render json: @commenttl.errors, status: :unprocessable_entity } end end end 省略
comments_controller.rb
def create @comment = current_user.comments.build(comment_params) @topic = @comment.topic @notification = @comment.notifications.build(user_id: @topic.user.id ) # クライアント要求に応じてフォーマットを変更 respond_to do |format| if @comment.save format.html { redirect_to topic_path(@topic), notice: 'コメントを投稿しました。' } format.json { render :show, status: :created, location: @comment } # JS形式でレスポンスを返します。 format.js { render :index } # pusherを使って通知件数をリアルタイムで更新させる Pusher.trigger("user_#{@comment.topic.user_id}_channel", 'notification_created', { unread_counts: Notification.where(user_id: @comment.topic.user.id, read: false).count }) else format.html { render :new } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end 省略
通知を確認するための、お知らせ一覧ページの記述はこのようにしています。
発生している問題の項目で詳細を記載しますが、ここでの記述方法で困っています。
notifications/index.html.erb
html
1<% @notifications.each do |notification| %> 2 <p> 3 <%= notification.comment.user.try(:name) %>さんが 4 あなたの投稿(<%= link_to "#{notification.comment.topic.title}", topic_path(notification.comment.topic, notification_id: notification.id) %>)にコメントしました。 5 </p> 6 <% end %>
###発生している問題・エラーメッセージ
お知らせ一覧ページで、複数(トピックとタイムライン)の通知を表示する方法がわかりません。
今のHTMLの記述ではトピックにコメントがあった際にしかお知らせを表示することができないし、タイムラインにコメントがあった際に、お知らせ一覧に遷移すると当然エラーになってしまいます。
どのように記述すればいいのでしょうか?
それとも今回の実装したやり方(作成方針)がそもそも間違っているのでしょうか?
説明が分かりづらい点もあるかとは思いますが、ご教授のほどよろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。