6 months ago
The following module allows you to call *_count methods on any ActiveRecord Object.
i.e @post.comments_count instead of @post.comments.count

It looks kinda stupid and unnecessary but comes in handy if you have(!) to specify a method by passing a symbol. In my case I was using this in JSON serialization parameters.
@user.to_json :methods => [:post_count, :comment_count]
The module also takes care of the respond_to? method by checking if the given association exists.
module AssocationCounts
  
  def respond_to?(name, include_private=false)
    if as = get_association(name)
      !self.class.reflect_on_association(as).nil?
    else
      super
    end
  end

  def method_missing(name, *args, &block)
    if respond_to?(name) && as = get_association(name)
      self.send(as).count
    else
      super
    end
  end

  private

  def get_association(name)
    if md = name.to_s.match(/^(.+)_count$/)
      md[1].to_sym
    end
  end
  
end

class ActiveRecord::Base; include AssocationCounts; end

Update: made get_association private
comments
blog comments powered by Disqus