的Rails + UUID +预先加载

问题描述:

我有2种型号在我的Rails应用程序,一个带有UUID主键:的Rails + UUID +预先加载

class User < ActiveRecord::Base 
    belongs_to :country, :foreign_key => 'country_uuid' 
end 

class Country < ActiveRecord::Base 
    set_primary_key :uuid 
    has_many :users 
end 

当我尝试类似的东西:

<% @user = User.find :first, :include => [:country] %> 
<%= @user.country.name %> 

我有好结果,但我在日志文件中看到2个请求。当我们更改UUID密钥的ID密钥时,为什么预先加载不起作用?

User Load (0.4ms) SELECT `users`.* FROM `users` LIMIT 1 
Country Load (0.4ms) SELECT `countries`.* FROM `countries` WHERE (`countries`.`uuid` = '1') 

而且我会碰到这样的:

User Load (0.4ms) SELECT `users`.* FROM `users` INNER JOIN countries ON countries.uuid = users.country_uuid LIMIT 1 

有没有解决办法? 如果我更改id密钥的uuid密钥,但保留字符串格式以存储uuid,它会好吗?

感谢,

使用联接,而不是包括获得内加入

包括总是发出第二个查询,但不是n + 1个查询(懒惰)

为您准备的方向用户 - > 1个国家就不是那么重要

,但如果你要去另一个方向的国家 - >许多用户

country = Country.first 
# => select countries.* from countries where id = xxxx limit 1; 
country.users.each do 
    # select users.* from users where user_id = xxxx; 
    # this could be bad because of lazy loading, one query per iteration 
end 

# vs... 
country = Country.first.includes(:users) 
# => select countries.* from countries where id = xxxx limit 1; 
# => select users.* from users where country_uuid IN (xxxx); 
country.users.each do 
    # users are all in memory 
end 

看到http://guides.rubyonrails.org/active_record_querying.html更多信息

我不认为你正在使用UUID应该有任何区别

+0

谢谢你的事实。 事实上,我尝试了很多用户,没关系:我对X用户有2个查询。 [:country]%> 用户负载(0.5毫秒)SELECT`users`。* FROM`users` 国家负荷(0.5毫秒)SELECT`countries`。* FROM`countries` WHERE(`countries`.`uuid` IN('1','2')) – 2011-12-16 16:39:08