Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save secretpray/6f2f7b69c6ea805f5662e7a50e2fc2ba to your computer and use it in GitHub Desktop.
Save secretpray/6f2f7b69c6ea805f5662e7a50e2fc2ba to your computer and use it in GitHub Desktop.
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