Ruby on Rails Thursday, August 20, 2015



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`:

http://api.rubyonrails.org/classes/ActiveRecord/Reflection/ClassMethods.html#method-i-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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/06155404-5fc0-4a86-92b2-9416a280b7d8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment