如何通过rails中的自定义连接来加载对象?

时间:2008-09-24 22:09:49

标签: sql ruby-on-rails ruby activerecord

背景

正常的铁路集合急切加载的方式如下:

Person.find(:all, :include=>:companies)

这会生成一些

的sql
LEFT OUTER JOIN companies ON people.company_id = companies.id

问题

但是,我需要一个自定义联接(如果我使用find_by_sql也会出现这种情况),所以我不能使用香草:include => :companies

自定义连接/ sql将获取我需要的所有数据,但是如何告诉activerecord它属于关联的Company对象而不仅仅是一堆额外的行?

更新

我需要在连接中添加其他条件。像这样:

SELECT blah blah blah
LEFT OUTER JOIN companies ON people.company_id = companies.id AND people.magical_flag IS NULL 
<Several other joins>
WHERE blahblahblah

4 个答案:

答案 0 :(得分:7)

您是否可以使用ActiveRecord添加连接条件?

例如,我有一个非常复杂的查询使用几个相关记录,它通过组合条件和包含指令工作正常

Contractors.find(
  :all, 
  :include => {:council_areas => :suburbs},
  :conditions => ["suburbs.postcode = ?", customer.postcode]                 
)    

假设:

  1. 承包商has_many CouncilAreas
  2. CouncilAreas has_many Suburbs
  3. 此联接返回由 customer.postcode 标识的郊区的承包商。

    生成的查询如下所示:

    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')
    

    (注意:为简洁起见,我编辑了列表。)

答案 1 :(得分:3)

您可以使用以下内容来获得适当的左外连接语法魔法。

Person.reflect_on_association(:companies).options[:conditions] = 'people.magical_flag IS NULL'

答案 2 :(得分:2)

我不确定这是你想要的(我不是100%确定我理解你的问题以及你想要完成的事情)但是:

如何同时提供:joins:includes

Person.find( :all, :joins => 'LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_', :includes => :companies )

或AR3方式:

Person.includes(:companies).joins('LEFT OUTER JOIN companies ON people.company_id = companies.id AND _pass_custom_conditions_here_')

答案 3 :(得分:1)

您是否可以详细说明您要使用此查询完成的内容?

另请查看find的:join选项。它允许您指定表的连接方式。 link text

使用时请注意:include,Rails 2.1中的行为会有所改变,并且当与引用包含表的:conditions选项一起使用时可能会导致一些问题。 link textlink text是Pivotal的两篇文章,提到了这个问题。