Description
The Collection concern's load_collection and load_post methods make multiple database calls per request, including repeated PostType.find_by lookups that aren't cached. This creates unnecessary database load, especially for high-traffic collections.
Current code
lib/bunko/controllers/collection.rb:49-50:
@post_type = PostType.find_by(name: @collection_name) # DB call #1
# ...
base_query = post_model.published.by_post_type(@collection_name) # DB call #2 (joins post_types)
Problems this causes
- Multiple database calls in a single action
- PostType lookup happens on every request (these rarely change)
- No guidance on N+1 prevention for associations
- Unnecessary JOIN in
by_post_type scope when we already have the PostType
- Could be slow for high-traffic sites
Pros of refactoring
- Fewer database queries per request
- Better performance for high-traffic collections
- Lower database load
- Potential for significant speedup with caching
- Better example for users building on top of Bunko
Cons of refactoring
- Adds complexity with caching
- Need to handle cache invalidation
- May need configuration for cache strategy
Recommended approach
Option A - Cache PostType lookups:
def find_post_type(name)
Rails.cache.fetch("bunko/post_type/#{name}", expires_in: 1.hour) do
PostType.find_by(name: name)
end
end
Option B - Use post_type_id once we have it:
@post_type = PostType.find_by(name: @collection_name)
base_query = post_model.published.where(post_type_id: @post_type.id)
Option C - Combine both approaches for maximum performance
Also consider adding documentation or helper methods for eager loading common associations to prevent N+1s.
References
lib/bunko/controllers/collection.rb:49-50
lib/bunko/controllers/collection.rb:92-98
Description
The Collection concern's
load_collectionandload_postmethods make multiple database calls per request, including repeatedPostType.find_bylookups that aren't cached. This creates unnecessary database load, especially for high-traffic collections.Current code
lib/bunko/controllers/collection.rb:49-50:Problems this causes
by_post_typescope when we already have the PostTypePros of refactoring
Cons of refactoring
Recommended approach
Option A - Cache PostType lookups:
Option B - Use post_type_id once we have it:
Option C - Combine both approaches for maximum performance
Also consider adding documentation or helper methods for eager loading common associations to prevent N+1s.
References
lib/bunko/controllers/collection.rb:49-50lib/bunko/controllers/collection.rb:92-98