Question about records count

Hi. I have few models - user, task, file

class User < ActiveRecord::Base
has_many :tasks
end

class Task < ActiveRecord::Base
belongs_to :user
has_and_belongs_to_many :files
end

class File < ActiveRecord::Base
has_and_belongs_to_many :tasks
end

I want to know files count for some user. is there some ‘right’ way to
do it without getting all tasks and looping it?

P.S. there is really many tasks and files.

sl_bug wrote in post #977638:

I want to know files count for some user. is there some ‘right’ way to
do it without getting all tasks and looping it?

P.S. there is really many tasks and files.

ActiveRecord includes aggregate calculations for this purpose that
perform the counts, sums, averages, etc. at the SQL layer:

http://railsapi.com/doc/rails-v3.0.3/classes/ActiveRecord/Calculations.html

Yea, but how to use it with such associations?

If you are using rails 3, maybe this will help you:

http://railscasts.com/episodes/202-active-record-queries-in-rails-3

seems like i found how to do it for one user

File.where(:users => {:id => 1}).count(:all, :include => {:tasks
=> :user})

but how to get hash with ‘user’ -> ‘files count’ using one query,
or may be even use something like counter cache.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs