rails has_many通过创建双连接,如何优化?

时间:2012-10-26 20:10:11

标签: ruby-on-rails activerecord

我有一种情况,即学校和EventLeg记录通过照片绑定在一起,属于给定的事件。

class Photo < ActiveRecord::Base
  belongs_to :event
  belongs_to :event_leg
  has_and_belongs_to_many :schools
end
class Event < ActiveRecord::Base
  has_many :event_legs, :through => :photos, :group => 'event_legs.id'
  has_many :photos
end
class School < ActiveRecord::Base
  has_and_belongs_to_many :photos
  has_many :events, :through => :photos
  has_many :event_legs, :through => :photos
end
class EventLeg < ActiveRecord::Base
  has_many :photos
  has_many :schools, :through => :photos
end

我需要在活动中获得特定活动中出现的学校。

@event = Event.find 4088
@event.schools.joins(:photos).where('photos.event_leg_id' => 28034)

这会导致SQL将photos_schools表连接两次,一次加入schools,一次连接到photos

SELECT DISTINCT `schools`.* FROM `schools` 
INNER JOIN `photos_schools` `photos_schools_join` ON `photos_schools_join`.`school_id` = `schools`.`id` 
INNER JOIN `photos` `photos_schools_2` ON `photos_schools_2`.`id` = `photos_schools_join`.`photo_id` 
INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id` 
INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id` 
WHERE `photos`.`event_id` = 4088 AND `photos`.`event_leg_id` = 28034

photos_schools的第二次加入 - &gt;照片是不必要的,以下查询做同样的事情并且更快:

SELECT DISTINCT `schools`.* FROM `schools` 
INNER JOIN `photos_schools` ON `schools`.`id` = `photos_schools`.`school_id` 
INNER JOIN `photos` ON `photos_schools`.`photo_id` = `photos`.`id` 
WHERE `photos`.`event_id` = 4088 AND photos.event_leg_id = 28034;

那么为什么AR会创建第二组连接,我该如何让它停止?

1 个答案:

答案 0 :(得分:1)

尝试跳过连接(:照片),我想它应该可以正常工作

     @event.schools.where('photos.event_leg_id' => 28034)