LoginSignup
2
2

More than 5 years have passed since last update.

RailsでRedisを使ってpvカウント

Posted at

初めに

railsでredisを使ってpv数をカウントする機能を実装してみました。

設定

redisをインストールする

gem 'redis-rails'

bundle install

実装

controllersのconcernsに

count_pv.rbファイルを作って

中に

module CountPv
    extend ActiveSupport::Concern

    def count_pv(action,controller)
        redis = Redis.new
        count = redis.get "count_#{controller}_#{action}"
        redis.set "count_#{controller}_#{action}", count.to_i + 1
        p redis.get "count_#{controller}_#{action}"
    end 
end 

pvカウントしたいコントローラーで

users_controller.rb
class UsersController < ApplicationController
  include CountPv

  def index
    count_pv("index", "users")
  end

  def index_a
    count_pv("index_a","users")
  end 
end

みたいにする。

これでカウントできる。

終わりに

redisの使い方がわからないんですがこれって

redis-railsをbundle installすればredisって勝手に起動するんですかね?

あとログが全くでないのはデフォルトなのかな?

なんのログも出ないけど一応使えてるのが気持ち悪いし起動しなくても使えるからほんとにredis使えてるのか不安になる(笑)

2
2
2

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
2
2