On Tue, Sep 16, 2008 at 9:23 PM, surge <[EMAIL PROTECTED]> wrote:

>
> That would be nice to use a counter cache, but the problem is (as it
> turns out), I have two counts to maintain. One is the total number of
> issues in a ticket and the other, the number of completed issues. The
> latter needs a condition. I guess I can't use counter caches?


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

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to