Last active
May 14, 2021 05:52
-
-
Save secretpray/6f2f7b69c6ea805f5662e7a50e2fc2ba to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Models: | |
------- | |
1) | |
user.rb | |
has_many :recipes | |
2) | |
recipe.rb # add counter_cache: true to recalculate posts_count field in user table | |
belongs_to :user, counter_cache: true | |
Migration: | |
--------- | |
bin/rails g migration add_recipes_count_to_users recipes_count:integer | |
class AddRecipesCountToUsers < ActiveRecord::Migration[6.1] | |
def change | |
add_column :users, :recipes_count, :integer, default: 0, null: false | |
end | |
end | |
bin/rails db:migrate | |
Update to reset counter: | |
------------------------ | |
rails c - recalculate recipes_count for all existing posts and users | |
User.find_each { |user| User.reset_counters user.id, :recipes } | |
On/Off in Dev mode | |
------------------- | |
bin/rails dev:cache |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment