[Rails] 頁面瀏覽計次
舉例
頁面瀏覽計次,這邊以文章(post)舉例
例如在post中加入view_count
當計次的欄位
rails g migration add_view_count_to_posts view_count:integer
rake db:migrate
第一種方法、簡易寫法
可以使用increment
他的原始寫法如下,第一個變數是丟入欄位名稱,第二個參數丟每次增加的值
# [path] activerecord/lib/active_record/persistence.rb, line 310
def increment(attribute, by = 1)
self[attribute] ||= 0
self[attribute] += by
self
end
使用這個就可以直接增加了
def show
@post = Post.find(params[:id])
@post.increment!(:view_count)
end
留言