LoginSignup
3
2

More than 3 years have passed since last update.

railsで通知機能とその未読管理機能を開発

Posted at

やりたいこと

  • rails
  • 通知機能
    • 通知の種類は色々増える可能性あり
  • 通知の未読管理
    • 通知一覧を開いた時点で開封済みとする。もし未読のものがあればラベルをつける

仕様

全体の流れ

  • notificationテーブルを作成し、そこで通知情報と未読管理を行う
  • indexを開いたらopen_timeがnilのものを取得し、現在時刻を入れる
  • headerのアイコンを未読(open_timeがnil)ありだったらバッジをつけ、なしだったらバッジをつけない

通知のscheme

scheme.rb
  create_table "notifications", force: :cascade do |t|
    t.text "url"
    t.integer "to_user_id"
    t.integer "from_user_id"
    t.integer "notification_type"
    t.datetime "open_time"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end
  • open_timeに開いた時刻を入れてここがnilなら未読とする
  • 通知内容は最初contentカラムを設けてそのまま文言を入れるか迷ったが時間が経ってユーザー情報などが変わった際に変更が効かないのと中の情報に何が入っているのか将来分からなくなるのが嫌だったので変数を取得するように
  • urlで飛び先を指定する。もし特殊なメソッドを使いたい場合はroutesでメソッドを指定する

一覧を開いたらopen_timeに時間を入れる

app/controllers/notifications_controller.rb
    unread_notifications = @notifications.where(open_time: nil)
    unread_notifications.each do |unread_notification|
      unread_notification.open_time = Date.today.to_time
      unread_notification.save
    end

上記繰り返し処理で現在時刻を入れていく

headerにて未読がある場合とアイコンを出しわけ

app/controllers/application_controller.rb
@notification_count = Notification.where(to_user_id: current_user.id,open_time: nil).count

上記で未読数を取得

app/views/layouts/_header.html.erb
      <div class="mr-4">
        <% if @notification_count > 0 %>
          <%= image_tag('notification_icon_unread.png',class: "header_icon align-middle") %>
        <% else %>
          <%= image_tag('notification_icon.png',class: "header_icon align-middle") %>
        <% end %>
      </div>

0より上だったらバッジなし

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2