How to destroy... with has_many

There are models: member(id,project_id,user_id), project(id), user(id), somemodel(id, project_id, user_id).

I would like that when a member is deleted so somemodel (that has project_id and user_id the same as that member) is deleted also. How to do that?

To do that I would like has_many :somemodels, dependent: :destroy to be added to member , but I don't know the right parameters to give to has_many :somemodels in member class. has_many :somemodels, dependent: :destroy alone doesn't work as it tries to search for somemodel by member_id which is not present on the somemodels table and so the no column error occurs.

What would be the right has_many :somemodels ... to be added to Member?

Upvotes: 0

Views: 123

Answers (2)

DanneManne
DanneManne

Reputation: 21180

An alternative way could be to create a :through association for this specific relation, and then set that one to dependent: :destroy. I think it would be structured like this:

class Member < ActiveRecord::Base

  belongs_to :user
  belongs_to :project

  has_many :some_models, ->(member) { where(user_id: member.user_id) },
                         through: :project,
                         dependent: :destroy
end

I haven't tested it, but it seems right as far as I can see.

Upvotes: 1

hoangdd
hoangdd

Reputation: 509

I think you should add a after_destroy callback to Member model:

# In member model
class Member < ApplicationRecord
    after_destroy :also_destroy_somemodel
    ...

   def also_destroy_somemodel
       # Fast, use in case somemodel dont have any callbacks
       Somemodel.where(project_id: project_id, user_id: user_id).delete_all

       # Or
       # Slow, use in case somemodel has callback(s)
       # Somemodel.where(project_id: project_id, user_id: user_id).each &:destroy
   end
end

Hope it helps.

Upvotes: 0

Related Questions