Several ways to do it:
1. Use ActiveRecord Association Extensions
class Post
has_many :comments do
def total
proxy_association.target.size
end
end
end
Allows you to call proxy_association
object, and appends the method to the instance of comments
(so you can call @post.comments.total
)
2. Use :inverse_of
#app/models/post.rb
Class Post < ActiveRecord::Base
has_many :comments, inverse_of: :post
end
#app/models/comment.rb
Class Comment < ActiveRecord::Base
belongs_to :post, inverse_of: :comments
end
Allows you to reference parent object from self
(self.post.total_comments
)
3. Use "Eager Loading" (keeping objects in memory)
This is query-level, and alluded to in NitinJ's answer & this RailsCast:
Post.includes(:comments)
I think NitinJ's comments are better than mine here, as I only have experience in creating DB calls with .includes
(not using it in an association capacity)
BONUS - Counter-Cache -- use this instead of comments.count
- it stores the count in memory, which will remove an expensive DB call!