1

Railsアプリに2つのモデルがあり、1つは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を格納するために文字列形式を維持した場合、問題はありませんか?

ありがとう、

4

1 に答える 1

3

内部結合を取得するには、インクルードの代わりに結合を使用します

includeは常に2番目のクエリを発行しますが、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 に答える