ernie/ransack — Issue #33: Association is joined twice when only once is necessary
Author: ckeen-md
Created: 2011-10-17 19:33:55+00:00
State: open

The base table is `consumers`. We store roles in a `consumer_roles` table with a many-to-many association. They're joined through `consumer_roles_consumers`, which is basically a join table with created_at/modified_at timestamps.

I'm getting a duplicate join when I try to add the following two conditions:

1) consumer_roles.name = 'My Role'
2) consumer_roles_consumers.created_at < '2009-01-01 00:00:00'

It produces the following query:

SELECT DISTINCT `consumers`.* FROM `consumers` LEFT OUTER JOIN `consumer_roles_consumers` ON `consumers`.`id` = `consumer_roles_consumers`.`consumer_id` LEFT OUTER JOIN `consumer_roles` ON `consumer_roles`.`id` = `consumer_roles_consumers`.`consumer_role_id` LEFT OUTER JOIN `consumer_roles_consumers` `consumer_roles_consumers_consumers` ON `consumer_roles_consumers_consumers`.`consumer_id` = `consumers`.`id` WHERE ((`consumer_roles`.`name` = 'Senior Ambassador' AND `consumer_roles_consumers_consumers`.`created_at` < '2009-01-01 00:00:00')) LIMIT 50 OFFSET 0

Should the second condition not be applied to the first join of `consumer_roles_consumers`, removing the second join?