如何将has_one关联限制为单个记录 [英] How to limit has_one association to a single record
问题描述
我无法在has_one关系中仅保留一条记录
I am having trouble with retaining only a single record in a has_one relationship
示例
类别和问题
问题属于一个类别,以及一个类别有一个问题
A question belongs_to a category, and a category has_one question
实际上,尽管存在has_one关系,但我正在构建的系统中看到的情况是,我有多个属于一个类别的问题.
In reality as seen in a system i am building even though the has_one relationship exists, there comes a case where i have multiple questions that belong to a category.
has_one关系不应该将它们限制为仅一条记录吗?如果没有,那么我如何确保我始终保持一份记录?
Shouldn't the has_one relationship limit them to just one record? If not, then how can i make sure that i always keep one record?
编辑
请注意,问题模型对类别ID具有唯一性规则,并且仍然我发现多个记录的案例指向相同的类别ID.
Please note that question model has a uniqueness rule on the ID of category and STILL i found cases of multiple records that point to same category ID.
那怎么可能?
编辑2
模型概述
class Event < ApplicationRecord
has_one :travel_time, :inverse_of => :event, dependent: :destroy
end
class TravelTime < ApplicationRecord
belongs_to :event, :inverse_of => :travel_time
validates_uniqueness_of :event_id, allow_nil: true
end
编辑3
方法用于保存旅行时间记录
method in event model used to save the travel time record
def store_travel_times(body)
travel_times = self.build_travel_time
# get travel times
...
if !travel_times.save
logger.error "..."
end
end
用于查找多个记录的查询
Query used to find the multiple records
2017-05-04T13:39:15.277063 #50567] DEBUG -- : TravelTime Load (0.4ms) SELECT "travel_times".* FROM "travel_times" WHERE "travel_times"."event_id" = $1 [["event_id", 3105]]
推荐答案
如注释中所述,创建db级约束以检查列的唯一性并避免创建多个记录.您需要使用以下代码创建迁移文件:
As discussed in the comments, create db level constraint to check uniqueness of a column and avoid multiple records creation. You need to create a migration file with below code:
add_index :travel_times, :event_id, unique: true
希望有帮助.
这篇关于如何将has_one关联限制为单个记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!