Rails Has_many Through Association With Counter Cache Argument
Counter cache argument prevents you from making unnecessary
SELECT COUNT (*) requests.
We want to make unnecessary @course.users call for each course.
Next association is a basic example for
:has_many, :through association.
We must add a counter cache for course, as users_count
After that we must add a field to Course model for storing users_count
Open the created migration file and set default value to 0 and prevent from nil records
1 2 3 4 5
After this step, @course.users will return 0, because we set the defaut value to it.
For fix this situation we must generate another migration file and fill @course.users_count field with correct values
Open the file and fill :users_count field
1 2 3 4 5 6 7 8 9 10 11
That’s all. Now you are storing users_count in database and cache it, so performance of your app increased.
Good for you!