How to limit has_one association to a single record

馋奶兔 提交于 2021-01-04 18:45:09

问题


I am having trouble with retaining only a single record in a has_one relationship

Example

Categories and question

A question belongs_to a category, and a category has_one question

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.

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?

EDIT

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.

How is that possible?

EDIT 2

Overview of the models

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

EDIT 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]]

回答1:


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

Hope it helps.



来源:https://stackoverflow.com/questions/43783347/how-to-limit-has-one-association-to-a-single-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!