少於 1 分鐘閱讀

舉例

頁面瀏覽計次,這邊以文章(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

第二種方法、使用Gem (考量IP訪問限制等問題)

impressionist

參考

  1. https://ruby-china.org/topics/8484
  2. http://apidock.com/rails/ActiveRecord/Persistence/increment
  3. https://github.com/charlotte-ruby/impressionist

更新時間:

留言