rails/rails — Issue #5249: finder_sql on the main association is ignored with nested associations in rails 3.1
Author: ciantainc
Created: 2012-03-02 21:38:24+00:00
State: open

Here is an example:

class TargetCollege < ActiveRecord::Base
has_many :doc_targets,
:finder_sql => proc {"select * from docs_targets
WHERE target_id IN (#{self.id}, 0)'"}
#nested association
has_many :documents, :through => :doc_targets
}

Query on 'has_many: doc_targets' produces the following sql as expected using finder_sql:
select * from docs_targets WHERE target_id IN (2, 0)

But query on 'has_many :documents', ignores the finder_sql as show below:

SELECT `documents`.* FROM `documents` INNER JOIN `docs_targets` ON `documents`.`id` = `docs_targets`.`document_id` WHERE `docs_targets`.`target_id` = 2

Correct sql should include what is specified in finder_sql "IN (2, 0)" as show below:
SELECT `documents`.* FROM `documents` INNER JOIN `docs_targets` ON `documents`.`id` = `docs_targets`.`document_id` WHERE `docs_targets`.`target_id` IN (2, 0)

Is this a bug and is there a fix for it?
Thanks