0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

投稿の閲覧数カウント機能

Last updated at Posted at 2026-01-10

ゴール

誰かが詳細ページを開くたびに総カウント数が1ずつ増えていく機能

開発環境

tweetsController,TweetModel,tweetsテーブル

事前準備

tweetsテーブルにeturanカラム(総閲覧回数を保存するためのカラム)を追加してもらいます。

ターミナル
rails generate migration AddEturanToTweets eturan:integer
#tweetsテーブルにeturanカラム(総閲覧回数を保存するためのカラム)を追加
rails db:migrate
#マイグレーションを実行

実装

カウントしてカラムに+1し続ける機能

app/controllers/tweets_controller.rb
  before_action :apude, only:[:show]
#詳細ページを開く前にapudeアクションを実行する。

  def apude
    @tweet = Tweet.find(params[:id])
    tweet = @tweet
    #tweetという文字に@tweetを代入する。
    if tweet.eturan == nil
      tweet.update!(eturan: 1)
      #投稿のeturanカラムの中身が最初は空っぽ(nil)なので1で上書きする。
      redirect_to tweet_path(tweet)
    else
      new_eturan = @tweet.eturan + 1
      #開こうとしている詳細ページのeturanカラムに+1してnew_eturanという名前に代入する。
      @tweet.update(eturan: new_eturan)
      #eturanにnew_eturanの中身を代入、閲覧数が1増えていく。
    end
  end
app/views/tweets/index.html.erb
<p>総閲覧数<%= @tweet.eturan %></p>
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?