Denis Policarpo
Denis Policarpo

Reputation: 153

Dependent destroy to tables with more than one references

I have a table Atribuition with 2 references from User table.

class Attribuition < ApplicationRecord
  belongs_to :user, class_name: 'User', foreign_key: 'user_id'
  belongs_to :not_rated, class_name: 'User', foreign_key: 'not_rated_id'
end

The User model:

class User < ApplicationRecord
  has_many :attribuitions, dependent: :destroy
end

When i destroy an user marked in not_rated i want it to be destroyed, but it just happens when i destroied an user marked as user_id, then the attribute row is deleted. I wanna make dependent:: destroy to work for many references of same model. That is possible?

My migration is:

class CreateAttribuitions < ActiveRecord::Migration[5.2]
  def change
    create_table :attribuitions do |t|
      t.references :user
      t.references :not_rated, index: { unique: true }

      t.timestamps
    end

  end
end

Upvotes: 0

Views: 510

Answers (1)

ray
ray

Reputation: 5552

Edit:

First you do following change as rails use convention over configuration

class Attribuition < ApplicationRecord
-  belongs_to :user, class_name: 'User', foreign_key: 'user_id'
+  belongs_to :user
end

Changes needed

When you mention has_many :attribuitions, dependent: :destroy by side of User model class_name will be Attribuition and foreign_key will be user_id stored in attributions table.

So if you need to destroy attribuitions related by foreign_key not_rated_id & user_id then you need following changes.

class User < ApplicationRecord
  has_many :attribuitions, dependent: :destroy # default foreign_key is user_id
  has_many :not_rated_attribuitions, foreign_key: 'not_rated_id', dependent: :destroy
end

Upvotes: 1

Related Questions