急切加载并在rails中执行后续映射并不急于加载

时间:2015-07-04 08:38:51

标签: ruby-on-rails-4 activerecord

说我有这样的模特。

Photo
  has_many :appearances
  def people 
    appearances.map{|p| p.person.name}
  end
end

Person
  has_many :appearances
end

Appearance
  belongs_to :person
  belongs_to :photo
end

当我尝试加载照片时,我看到像活动记录这样的高级查询正在进行相应的连接

Photo.eager_load({:appearances => :person}).find(ids)

然而,当我尝试像这样手动映射响应时

Photo.eager_load({:appearances => :person}).find(ids).map{|p| p.people}

我看到activerecord正在进行n + 1查询,为集合中的每张照片选择所有外观

  SQL (0.6ms)  SELECT `photos`.`id` AS t0_r0, `photos`.`time_created` AS t0_r1, `photos`.`sub_location` AS t0_r2, `photos`.`state` AS t0_r3, `photos`.`author` AS t0_r4, `photos`.`copyright_notice` AS t0_r5, `photos`.`country_primary_location_name` AS t0_r6, `photos`.`date_created` AS t0_r7, `photos`.`city` AS t0_r8, `photos`.`caption` AS t0_r9, `photos`.`by_line` AS t0_r10, `photos`.`abstract` AS t0_r11, `photos`.`name` AS t0_r12, `photos`.`province` AS t0_r13, `photos`.`visible` AS t0_r14, `photos`.`filename` AS t0_r15, `photos`.`folder` AS t0_r16, `photos`.`image_file_name` AS t0_r17, `photos`.`image_content_type` AS t0_r18, `photos`.`image_file_size` AS t0_r19, `photos`.`image_updated_at` AS t0_r20, `photos`.`image` AS t0_r21, `photos`.`position` AS t0_r22, `photos`.`event_id` AS t0_r23, `photos`.`created_at` AS t0_r24, `photos`.`updated_at` AS t0_r25, `photos`.`price_mod` AS t0_r26, `photos`.`never_discount` AS t0_r27, `photos`.`visible_and_public` AS t0_r28, `photos`.`make_public_on` AS t0_r29, `photos`.`is_shoppable` AS t0_r30, `photos`.`is_visible` AS t0_r31, `photos`.`keywords` AS t0_r32, `photos`.`tag_names` AS t0_r33, `appearances`.`id` AS t1_r0, `appearances`.`photo_id` AS t1_r1, `appearances`.`person_id` AS t1_r2, `appearances`.`position` AS t1_r3, `appearances`.`created_at` AS t1_r4, `appearances`.`updated_at` AS t1_r5, `appearances`.`visible_and_public` AS t1_r6, `people`.`id` AS t2_r0, `people`.`name` AS t2_r1, `people`.`title` AS t2_r2, `people`.`created_at` AS t2_r3, `people`.`updated_at` AS t2_r4, `people`.`slug` AS t2_r5, `people`.`has_one_photo` AS t2_r6, `people`.`appearance_count` AS t2_r7 FROM `photos` LEFT OUTER JOIN `appearances` ON `appearances`.`photo_id` = `photos`.`id` LEFT OUTER JOIN `people` ON `people`.`id` = `appearances`.`person_id` WHERE `photos`.`id` = 1 AND `photos`.`id` IN (1)
  Person Load (0.4ms)  SELECT  `people`.* FROM `people`  WHERE `people`.`id` = 2 LIMIT 1
  Person Load (0.4ms)  SELECT  `people`.* FROM `people`  WHERE `people`.`id` = 3 LIMIT 1
  Person Load (0.4ms)  SELECT  `people`.* FROM `people`  WHERE `people`.`id` = 4 LIMIT 1
Completed 200 OK in 483ms (Views: 1.2ms | ActiveRecord: 22.9ms)

0 个答案:

没有答案