1

我的 rails 应用程序中有 2 个模型,一个带有 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

有解决方法吗?如果我将 uuid 键更改为 id 键,但保留字符串格式来存储 uuid,可以吗?

谢谢,

4

1 回答 1

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 的事实应该有任何区别

于 2011-12-16T16:26:28.310 回答