微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 的存在。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。