如何在 rails 中制作 "Unique many to many self joint"?

How to make a "Unique many to many self joint" in rails?

我已经阅读了 多对多的自我关节。我的问题是我需要它是独一无二的。

# app/models/word.rb
class Word < ApplicationRecord
    has_and_belongs_to_many(:defined, 
    class_name: 'Word', 
    join_table: 'defined_definers', 
    association_foreign_key: 'defined_id', 
    foreign_key: 'definer_id')
  has_and_belongs_to_many(:definers, 
    class_name: 'Word', 
    join_table: 'defined_definers', 
    association_foreign_key: 'definer_id', 
    foreign_key: 'defined_id')
end

这应该引发错误或不被执行:

word.definers << word.defined.first

否则,我的应用程序中可能会出现更严重的无法检测到的错误。

为了避免重复,您需要在数据库 add_index :defined_definers, [:definer_id, :defined_id], unique: true 中添加一个唯一索引,或者将每个地方的代码更改为 word.definers << word.defined.first unless word.definers.include?(word.defined)