2011-12-16 73 views
1

我有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,它會好嗎?

感謝,

回答

3

使用聯接,而不是包括獲得內加入

包括總是發出第二個查詢,但不是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個查詢。 <%@users = User.find:all,:include => [:country]%> <%@ users.each do | user | %> <%= user.country.name%> <% end %> 用戶負載(0.5毫秒)SELECT`users`。* FROM`users` 國家負荷(0.5毫秒)SELECT`countries`。* FROM`countries` WHERE(`countries`.`uuid` IN('1','2')) – 2011-12-16 16:39:08