has_one模型关联未在关联模型中强制执行“ one”?

问题描述

我有以下

class User < ApplicationRecord

  has_one :physician

end

class Physician < ApplicationRecord

  belongs_to :user

end

由于一个用户只能有一个医生,所以我惊讶于可以使用相同的用户ID创建多个医生记录。

这是为什么?以及如何预防呢?

解决方法

belongs_to关联不保证任何值都是唯一的。它仅规定关联存储在 this 模型表的外键中,因此只能具有单个值。

has_one实际上也没有提供任何保证。它只是指定在 other 表上引用 this 表。如果另一个表上有多个匹配的行,它将选择最后一个。

如果要对每个表强制执行唯一性,则需要验证:

class Physician < ApplicationRecord
  belongs_to :user
  validates_uniqueness_of :user_id
end

以及指向actually guarantee uniqueness on the database level的数据库索引:

class AddUniqueIndexToPhysicians < ActiveRecord::Migration[6.0]
  def change
    add_index :physicians,:user_id,unique: true
  end
end
,

2020-08-29 16:52:46.301 ERROR 25020 --- [ctor-http-nio-4] a.w.r.e.AbstractErrorWebExceptionHandler : [b339763e-1] 500 Server Error for HTTP GET "/api/v1/integration/notfound" org.springframework.web.client.HttpClientErrorException: 404 Entity not found. at com.stevenpg.restperformance.webflux.Service.lambda$badEndpoint$0(Service.java:30) ~[main/:na] Suppressed: reactor.core.publisher.FluxOnAssembly$OnAssemblyException: Error has been observed at the following site(s): |_ checkpoint ⇢ 404 from GET https://httpbin.org/status/404 [DefaultWebClient] |_ checkpoint ⇢ Handler com.stevenpg.restperformance.webflux.EndpointRouter$$Lambda$445/0x00000008003ae040@7799b58 [DispatcherHandler] |_ checkpoint ⇢ HTTP GET "/api/v1/integration/notfound" [ExceptionHandlingWebHandler] 可能不应该关联Physician

user_id
默认情况下,Rails 5和更高版本需要

class User belongs_to :physician # has a physician_id column end class Physician has_many :users # has no mention of user_id in its schema end 。如果用户可以在没有医生的情况下上船,而您需要禁用此功能:

belongs_to

然后,仅在某些情况下验证class User belongs_to :physician,optional: true end 的存在。