Rails自动加载has_one关系

时间:2018-05-20 21:02:10

标签: ruby-on-rails ruby devise

  • Ruby版本2.4.4
  • Rails版本5.1.4
  • Devise version 4.4.3

我的申请中遇到了一个奇怪的问题。简而言之,每当我加载用户记录时,它都会自动加载相关的位置记录。

用户模型:

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_one :location, as: :owner
end

位置模型:

class Location < ApplicationRecord
  belongs_to :owner, polymorphic: true, required: false
end

在rails控制台中,如果我只输入User.last,我会看到两个查询:

User Load (1.5ms)  SELECT  "users".* FROM "users" WHERE "users"."deleted_at" IS NULL ORDER BY "users"."id" DESC LIMIT $1  [["LIMIT", 1]]

紧接着

Location Load (6.8ms)  SELECT  "locations".* FROM "locations" WHERE "locations"."owner_id" = $1 AND "locations"."owner_type" = $2 LIMIT $3  [["owner_id", 9], ["owner_type", "User"], ["LIMIT", 1]]

如果我注释掉devise行,则不再发生。有什么可能导致这种情况的任何解释?两种型号都没有定义默认范围。

0 个答案:

没有答案