LoginSignup
14
11

More than 3 years have passed since last update.

既読・未読判定機能の実装

Last updated at Posted at 2020-06-19

既読・未読機能の実装方法

まず、簡単なブログ機能のあるrailsアプリがあるとします。
このアプリのブログ詳細画面に遷移した際に、既読となるような仕様で実装していきたいと思います。
※既読/未読機能を実装するために必要なコードのみ載せています。

ER図

9E62416E-211A-4FC1-B849-AE2B019E9D50_4_5005_c.jpeg

テーブル

  • user
  • blog
  • read

既読機能を実装するにあたって、userテーブルとblogテーブルの中間テーブルが必要になります。
そこで、readテーブルを作成しました。

readテーブルのカラム

  • user_id
  • blog_id
  • complete(boolean型)

completeカラムをboolean型とし、既読/未読を真偽値で取得するようにしました。

モデル

user.rb
class User < ApplicationRecord
  has_many :blogs
  has_many :reads, dependent: :destroy
end
blog.rb
class Blog < ApplicationRecord
  belongs_to :user
  has_many :reads, dependent: :destroy
end

read.rb
class Read < ApplicationRecord
  belongs_to :user
  belongs_to :blog
end

コントローラーの設定

blogs_controller
class BlogsController < ApplicationController

  def show
    if Read.create(blog_id: @blog.id, user_id: current_user.id) 
      @read = Read.update(complete: true)
    end
  end

showメソッドに、「ブログ詳細画面に飛んだら、現在ログインしているユーザーidとブログidが取得された、readメソッドが作成される。readメソッドが作成されたら、ブログが既読の状態にアップデートされる。」という記述をし、@readに格納します。
complete: true = '既読'

ビューの設定

show.html.erb
<%= @read ? '既読' : '未読' %>

@read ? '既読' : '未読'」 は、三項演算子という記法で、「?」の前の記述(@read)が、
true(真)であれば:の左側の処理を実行('既読'という文字列の出力を実行)し、
false(偽)であれば:の右側の処理を実行('未読'という文字列の出力を実行)します。

以上のようにコードを記述してくと、ブログ詳細画面に遷移した際に
4FE0EDBE-6683-41E2-AE32-FB10EF2D5D40_4_5005_c.jpeg

このように「既読」という文字列を出力できるようになります。

14
11
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
14
11