Rails 4急切加载一个对象

时间:2015-01-06 22:43:00

标签: ruby-on-rails-4 rails-activerecord eager-loading

我试图从实例化对象中加载关联,即不是与父对象一起读取关联...

User.includes(:characters).first

...推迟到我决定真正需要它并做类似的事情:

u = User.first
# Other stuff ...
u.eager_load(:characters)

在Rails 3中,我用这种方法增强了ActiveRecord:

def eager_load(*args)
  ActiveRecord::Associations::Preloader.new(self, *args).run
end

它工作正常。 Rails 4改变了这一部分,我将方法更新为:

def eager_load(*args)
  ActiveRecord::Associations::Preloader.new.preload(self, *args)
end

不幸的是,它现在做了一些奇怪的事情。看看:

2.1.2 :001 > u = User.first
[2015-01-06 23:18:03] DEBUG ActiveRecord::Base :   User Load (0.3ms)  SELECT  `users`.* FROM `users`  ORDER BY `users`.`id` ASC LIMIT 1
 => #<User id: 1, ...> 
2.1.2 :002 > u.eager_load :characters
[2015-01-06 23:18:07] DEBUG ActiveRecord::Base :   Character Load (0.2ms)  SELECT `characters`.* FROM `characters` WHERE `characters`.`user_id` IN (1)
[2015-01-06 23:18:07] DEBUG ActiveRecord::Base :   Character Load (0.3ms)  SELECT `characters`.* FROM `characters`
[2015-01-06 23:18:07] DEBUG ActiveRecord::Base :   Character Load (0.2ms)  SELECT `characters`.* FROM `characters`
 => [#<ActiveRecord::Associations::Preloader::HasMany:0x00000007c26d28 @klass=Character(id: integer, ...), @owners=[#<User id: ...], @reflection=#<ActiveRecord::Reflection::HasManyReflection:0x0000000496aa60 @name=:characters, ...(LOTS of stuff here)...] 

特别注意所有记录的双重SELECT。有没有办法解决这种行为或其他方法来做我想做的事情?

1 个答案:

答案 0 :(得分:1)

我有同样的问题,并追溯我的步骤,我注意到这可能是在控制台上运行此代码的工件。每个表达式都会被评估,但我们只对副产品感兴趣:如果是这种情况,请尝试:

u.eager_load(:characters); nil

我希望它有所帮助,我目前正在研究这个问题,所以这是我迄今为止唯一的观察。