본문 바로가기

Archived(Programming)/Ruby on Rails(기초)

RubyOnRails 8) Impressionist 조회수 구현

RubyOnRails 8) Impressionist 조회수 구현


참고:

http://blog.naver.com/PostView.nhn?blogId=kbs4674&logNo=221042620689&categoryNo=78&parentCategoryNo=0&viewDate=&currentPage=1&postListTopCurrentPage=1&from=postView


게시글에 대한 조회수를 구현하기 위해 먼저 다음의 젬을 설치해준다.


1
2
3
4
Gemfile
 
gem 'impressionist'
$ bundle
cs


다음 다음의 명령어를 수행한다.


1
2
$ rails g impressionist
$ rails db:migrate
cs


그리고 Post.rb 파일로 가서 다음의  코드를 추가해준다.


1
2
3
4
5
6
7
8
9
10
11
12
/app/models/post.rb 
 ...
is_impressionable
def impression_count
   impressions.size
end
 
def unique_impression_count
   # impressions.group(:ip_address).size gives => {'127.0.0.1'=>9, '0.0.0.0'=>1}
   # so getting keys from the hash and calculating the number of keys
   impressions.group(:ip_address).size.keys.length #TESTED
end
cs


그리고 컨트롤러로 가서 다음을 추가해준다.


1
2
3
4
5
6
7
8
9
10
11
12
/app/controllers/posts_controller.rb
 
...
before_action :log_impression, :only=> [:show]
 
# 조회수 설정
def log_impression
    @hit_post = Post.find(params[:id]) 
    # this assumes you have a current_user method in your authentication system
    @hit_post.impressions.create(ip_address: request.remote_ip,user_id:current_user.id)
end
...
cs


마지막으로 view 파일에 해당 내용을 추가해준다.


1
<%= "#{@post.unique_impression_count}" %>
cs