これまでに作った機能について簡単にまとめていく。
今回は、
counter_cultureを使った子モデルのカウント機能
本記事ではいいねの数をカウント
いいね機能についてはこちら
使用モデル
Userモデル
| カラム | データ型 | |
|---|---|---|
| 1 | name | string |
| 2 | text | |
| 3 | password_digest | string |
Blogモデル
| カラム | データ型 | |
|---|---|---|
| 1 | title | string |
| 2 | content | text |
| 3 | likes_count | integer |
Likeモデル(中間テーブル)
| カラム | データ型 | |
|---|---|---|
| 1 | user_id | bigint |
| 2 | blog_id | bigint |
Gemの導入
gem 'counter_culture'
bundle installの実行
Gemに対応したカラムの作成
rails g counter_culture Blog likes_count
通常のカラムは使用できない
アソシエーションの作成
app/models/like.rb
class Like < ApplicationRecord belongs_to :user belongs_to :blog # 追加 counter_culture :blog end
以上で作成完了
