Chiara Ani
Chiara Ani

Reputation: 1093

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

I've read other answers of many to many self joints. My problem is I need it to be unique.

# 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

This should raise an error or not be executed:

word.definers << word.defined.first

Otherwise, I could have much worse undetectable errors in my app.

Upvotes: 0

Views: 43

Answers (1)

CraftyMousy
CraftyMousy

Reputation: 81

To avoid duplicates you either need to add an unique index in database add_index :defined_definers, [:definer_id, :defined_id], unique: true or change your code in every place to word.definers << word.defined.first unless word.definers.include?(word.defined)

Upvotes: 1

Related Questions