How to eager load objects with a custom join in rails?
Can you not add the join conditions using ActiveRecord?
For example, I have a quite complex query using several dependent records and it works fine by combining conditions and include directives
Contractors.find( :all, :include => {:council_areas => :suburbs}, :conditions => ["suburbs.postcode = ?", customer.postcode] )
Assuming that:
- Contractors have_many CouncilAreas
- CouncilAreas have_many Suburbs
This join returns the Contractors in the suburb identified by customer.postcode.
The generated query looks like:
SELECT contractors.*, council_areas.*, suburbs.*FROM `contractors` LEFT OUTER JOIN `contractors_council_areas` ON `contractors_council_areas`.contractor_id = `contractors`.id LEFT OUTER JOIN `council_areas` ON `council_areas`.id = `contractors_council_areas`.council_area_id LEFT OUTER JOIN `council_areas_suburbs` ON `council_areas_suburbs`.council_area_id = `council_areas`.id LEFT OUTER JOIN `suburbs` ON `suburbs`.id = `council_areas_suburbs`.suburb_id WHERE (suburbs.postcode = '5000')
(Note: I edited the column list for brevity).
You can use something like the following to get the appropriate left outer join syntactical magic.
Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'
I'm not sure it's what you want (I'm not 100% sure I've understood your question and what you want to accomplish) but:
What about providing both :joins
and :includes
?
Person.find( :all, :joins => 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_', :includes => :companies)
Or AR3 way:
Person.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')