简体   繁体   English

在has_one关联轨道上保存了多个条目

[英]more than one entry saved on has_one association rails

I am trying to create a has_one association among two model. 我正在尝试在两个模型之间创建has_one关联。

class User < ActiveRecord::Base
  has_one :emergency_contact
end

class EmergencyContact < ActiveRecord::Base
  belongs_to :user
end

when i try to test it through rails console more than one entries are saved for the emergency contact model for a single user. 当我尝试通过Rails控制台对其进行测试时,为单个用户的紧急联系人模型保存了多个条目。 Although when i retrieve it using User.emergency_contact only the first entry is returned. 虽然当我使用User.emergency_contact检索它时​​,仅返回第一个条目。 When saving how can i make it to rollback for more than one entry 保存时,如何使其回滚多个条目

You can simply validate uniqueness of user_id column in EmergencyContact : 您可以简单地在EmergencyContact验证user_id列的唯一性:

class EmergencyContact < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :user_id, allow_nil: true
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM