Hi, you can use a counter cache to track the total number of issues for
a given ticket. Next, you’ll perform the query for the open and closed
ticket counts. The counter cache will track the number of objects within
the database for a given model. Also, I would add index to the appropriate
tables. For example, I would add an index to the following table:
issues
At this time, you should have a foreign key on the issue table called ticket_id.
Thus, you’ll need to create a migration as follows:
script/generate migration add_indexes
Now, you’ll edit the migration file by adding the following to the following:
class AddIndexes < ActiveRecord:Migration
def self.up
add_index :issues, :ticket_id
end
def self.down
remove_index :issues, :ticket_id
end
end
Now, you’ll need to run the following command:
rake db:migrate
Next, I would create named_scope on the Issue Model:
class Issue < ActiveRecord::Base
named_scope :open , :conditions => { :closed = false }
named_scope :closed, :conditions => { :closed = true }
end
Lastly, you should be able to do the following:
Total number of issues for a given ticket.
ticket.issues.size # uses the counter cache
Total number of issues open for a given ticket.
ticket.issues.open.size # performs a database query
Total number of issues open for a given ticket.
ticket.issues.closed.size # performs a database query
Good luck,
-Conrad