渴望加载Rails 4 - 仍然是多个查询

时间:2015-11-10 14:24:48

标签: mysql ruby-on-rails ruby-on-rails-4

我有这段代码:

class User < ActiveRecord::Base
   has_many :people
end

class Person < ActiveRecord::Base
   belongs_to :user
end

def map_people people
   people.map {|person|
     map_person(person)
   }
end

def map_person person
   {
     :person_id => person.id,
     :user_id => person.user.id,
     :name => person.user.name
   }
end

当我跑步时:

map_people(Person.with_deleted.includes(:user))

我正在

 Person Load (1.4ms)  SELECT `people`.* FROM `people`
 User Load (2.5ms)  SELECT `users`.* FROM `users` WHERE `users`.`deleted_at` IS NULL AND `users`.`id` IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 76, 78, 79, 80, 81, 83, 84, 85, 87, 88, 89, 90, 91, 92, 75, 93, 94, 95, 96, 97, 98, 99, 100, 101, 104, 105, 106, 107, 108, 109, 112, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 127, 128, 135, 142, 143)  ORDER BY users.updated_at DESC
 User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.5ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 3  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.6ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 3  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.6ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.6ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 2  ORDER BY users.updated_at DESC LIMIT 1
 User Load (0.4ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 1  ORDER BY users.updated_at DESC LIMIT 1

以及更多SELECT&#39;用户&#39;。* FROM .....查询

Hos可以通过一个查询加载所有内容吗?

谢谢!

大卫

3 个答案:

答案 0 :(得分:1)

我会尝试使用eager_load来做这件事。这将首先将所有人拉入内存(使用一个查询),然后您可以迭代每个人,每次调用map_person方法。

这应该有效:

def map_people
  all_people = Person.eager_load(:user).with_deleted.to_a
  all_people.map { |person| map_person(person) }
end

如果您愿意,也可以将people数组传递给方法,如下所示:

def map_people(people)
  people.map { |person| map_person(person) }
end

all_people = Person.eager_load(:user).with_deleted.to_a
map_people(all_people)

答案 1 :(得分:0)

尝试运行

map_people(Person.with_deleted.preload(:user))

关于这个话题有一篇很好的文章btw:

http://blog.arkency.com/2013/12/rails4-preloading/

答案 2 :(得分:0)

对不起伙计们,我的错误(班级人员):

  def user
     @user ||= user_id ? User.with_deleted.find(user_id) : nil
  end

所以它总是再次加载