2016年11月9日 星期三

counter_cache 的使用

1, 在原有的group table裡,新增一個欄位取名叫posts_count
rails g migration add_posts_count_to_group posts_count:integer

# db/migrate/(一堆數字)_add_posts_count_to_group.rb
-   add_column :groups, :posts_count, :integer
+   add_column :groups, :posts_count, :integer, default: 0
rake db:migrate

# 這樣 group 這個資料表就多了 posts_count 這個欄位

2, 到Model 設定
# app/models/post.rb
- belongs_to :group
+ belongs_to :group, counter_cache: :posts_count

# 設定好 counter_cache: :posts_count (即剛才建立的欄位名稱);此後post 只要 create 跟 destroy,就會自動在 posts_count 欄位 +1 跟 -1

3, 到瀏覽器增刪post,並去終端機確認
rails c
a =  Group.find(1)
# 1為增刪的post的group
# 注意 posts_count: 的數字,代表資料庫posts_count欄位,隨posts的增刪而變動,如下
=> #<Group id: 1, title: "new group", description: "test", created_at: "2016-11-07 13:15:55", updated_at: "2016-11-07 13:15:55", user_id: 1, posts_count: 1>

4, 修改 views
# 假使你原本有用SQL 一篇篇抓post數量

<%= group.posts.count %>

# 那就改成這樣

<%= group.posts.size %>

參考:Rails 101

沒有留言:

張貼留言