おーしまブログ

プログラミングやってます

通知機能の実装

こんにちは、おーしまです。

今回は自動車レビューサイトに通知機能を実装したので、ご紹介します。

f:id:tomo_bb_aki0118115:20201208232926p:plain

自動車レビューサイトでは、フォローやいいねが機能がないので、コメントだけ通知機能が必要になります。よって新しく通知のテーブルを作成し、コメントを保存する際に、一緒に通知も保存します。

notificationsテーブルのマイグレーションファイル(通知のテーブル)

class CreateNotifications < ActiveRecord::Migration[6.0]
  def change
    create_table :notifications do |t|
      t.integer :car_id
      t.integer :comment_id
      t.integer :send_user_id
      t.integer :transmitted_user_id
      t.boolean :notice,                null: false, default: false
      t.timestamps
    end
  end
end
  • コメントされたレビューのid
  • コメントしたコメントのid
  • コメントをしたユーザーのid
  • コメントされたレビューを投稿したユーザーのid
  • 既読ならtrue、未読ならfalse のカラム

こんな感じでできました。
現時点では、通知にどんなコメントが来たのか掲載できていないので、コメントのidは使っておりません。
表示方法は、javascriptで通知ボタンを押した際に、current_user.id==transmitted_user_idとなっている通知を、非同期通信で集め、表示しています。

  def search_notification
    notifications = Notification.where(transmitted_user_id: current_user.id).order('created_at desc')
    send_user_names =[]
    notifications.each do |notification|
      send_user_names << notification.send_user.nickname
    end
    render json: {notifications: notifications, send_user_names: send_user_names} 
  end

javascriptにレスポンスとして送ってからは、idからユーザー名を取り出すことができなかったので、配列に入れて送っています)

表示する際、noticeがfalseだった場合、背景を薄緑色にして未読であることを表しています。
notification.js

  if (notification.notice) {
    childElement.setAttribute("style", "background-color: #ffffff;");
  }else{
    childElement.setAttribute("style", "background-color: #deffe0;");
  }

通知をクリックすると、コメントされたレビューの詳細ページに遷移します。その時に通知のfalseをtrueにupdateします。

childA.setAttribute("href", `/cars/${notification.car_id}?notification_id=${notification.id}`);
  def show
    @comment = Comment.new
    @comments = @car.comments.order('created_at desc')
    if params[:notification_id]
      @notification = Notification.where(params[:notification_id])
      @notification.update(notice: 'true')
    end
  end

レビューの詳細ページへ遷移するリンクのhref属性に、notification_idをパラメーターとして送信し、notification_idが送られてきた場合だけ、updateしています。



また、通知を集めた際に、falseがあれば、通知の右上に黄緑色の丸をつけ、未読通知があることを表しています。

@notifications = Notification.where(transmitted_user_id: current_user.id).where(notice: 'false') if user_signed_in?
   <% if @notifications.present? %>
     <div class='notice-false'></div>
   <% end %>

whereメソッドで、ログインしているユーザーの通知を集め、さらにnoticeがfalseになっている通知に絞ります。
ビューファイルで、@notifications(=未読通知)があれば、黄緑の丸を付けています。





今回はここまでです。
それではまた。

ここはどこ おれはだれ それに近いものがあんだよ 始めようとした奴らも迷い始めてる 怖がらせないでよ そりゃ甘くはないけど まだまだ 夢見ていい世界なんでしょ {UVERwould「ハイ!問題作」}