magnusvk/counter_culture — pull request #49 by Smudge (2014-04-16 18:04:59+00:00)
Title: Fix for issue where counter_culture_fix_counts with condition skips rows

Say we define something like this on our `Member` model:

````ruby
belongs_to :parent
counter_culture :parent,
column_name: Proc.new {|m| m.condition? ? 'members_count' : nil },
column_names: { ['members.condition = ?', true] => 'members_count' }
````

When we run `Member.counter_culture_fix_counts` we get a counts query like this:

````sql
SELECT parents.id, COUNT(memberships.id) LEFT JOIN memberships ON parents.id = memberships.parent_id WHERE members.condition = 't'
````

id | count
------------- | -------------
1 | 15
|
3 | 10

You'll notice that row number 2 gets skipped entirely, because the `WHERE` is applied to the outermost `SELECT` instead of the `JOIN`.

We compare the results of that counts query to our existing data, which runs its own query returning this result:

When we try to compare those counts with the existing counts, we get a row where our counts hash has a nil value, which is fine, because it will be set to 0.

Say, however, we are doing this in batches, with batch size of 2 (for the purpose of this explanation). Our 'count' query returns this:

id | count
------------- | -------------
1 | 15
|
3 | 10

However, our

| id | members_count |
| ------------- | ------------- |
| 1 | 999999 |
| 2 | 999999 |
| 3 | 999999 |