how to find what all associations have dependent: destroy associated with them from a concern

45 views
Skip to first unread message

Aravind Gopalakrishnan

unread,
Jul 18, 2015, 2:56:43 AM7/18/15
to rubyonra...@googlegroups.com
I am building a soft delete solution a la https://github.com/discourse/discourse/blob/master/app/models/concerns/trashable.rb . Right now I am manually finding which all associated models need to be deleted when a model is deleted and doing it manually in each model which of course is a not a good practice. How do I do it? I don't want to use a gem, I want to write logic in my own hands.

Taras Matsyk

unread,
Jul 20, 2015, 3:29:59 PM7/20/15
to rubyonra...@googlegroups.com
Hi Aravind,

I am not sure if I understood your question correctly but I will give a
try.
I think you want to delete all associated records with another type of
the Model.

class Body
has_many: boobs, dependent: :destroy
end

>> In this instance destroy parameter is responsible for generating/using code
that removes all dependent boob if the body instance is destroyed.


Did I get you right?

--
Posted via http://www.ruby-forum.com/.
Message has been deleted

Matt Jones

unread,
Aug 20, 2015, 7:10:56 PM8/20/15
to Ruby on Rails: Talk


On Saturday, 18 July 2015 01:56:43 UTC-5, Aravind Gopalakrishnan wrote:
I am building a soft delete solution a la https://github.com/discourse/discourse/blob/master/app/models/concerns/trashable.rb . Right now I am manually finding which all associated models need to be deleted when a model is deleted and doing it manually in each model which of course is a not a good practice. How do I do it? I don't want to use a gem, I want to write logic in my own hands.

The place to start is `reflect_on_all_associations`:


This will give you all the associations defined for the model. You can then request the option you're interested in thus:
```
klass.reflect_on_all_associations do |reflection|
  if reflection.options[:dependent]
    # do something with it
  end
end
```

--Matt Jones
Reply all
Reply to author
Forward
0 new messages