Optimize some ActiveRecord queries to prevent N + 1 queries