1

I have two models, Note and Group, with has_and_belongs_to_many relations. Many notes can be in one group, one note can belong to many groups.

How can i delete all notes belongs to only one group?

UPD:

Thanks, but i don't want to delete all notes in group. I want to delete notes, that belongs only to one group.

ertaquo
  • 130
  • 1
  • 1
  • 9

3 Answers3

1

Instantiate your group, then call clear on the association.

@group.notes.clear

Here's the documentation.

Substantial
  • 6,684
  • 2
  • 31
  • 40
  • Will it delete all notes in specified group? Or it will delete only notes, belongs **only** to this group? – ertaquo Jun 05 '13 at 05:43
  • Uh, what? It will disassociate all notes belonging to the group `@group`. It does not destroy the notes, just removes the association with `@group`. To destroy the notes, do `@group.notes.destroy_all`. – Substantial Jun 05 '13 at 05:57
  • Other words, let there are: groups 123 and 456, notes 111, 222, 333. Each note belongs to **both** groups. So, will Group.find(123).notes.destroy_all any notes? – ertaquo Jun 05 '13 at 07:11
  • `#destroy_all` will destroy the notes (from both groups). `#clear` will remove the notes from group 123, but not group 456. If you then `#clear` those notes from group 456, you will have orphaned notes (not associated with any group). – Substantial Jun 06 '13 at 02:15
1

You can also try this

@group.notes.destroy_all

OR

@group.notes.delete 
Deepika
  • 826
  • 6
  • 14
1

See the following stackoverflow question and answer regarding destroying associated data; in addition there is a plugin to protect some of your associations from being destroyed, I have used this plugin successfully on rails 2.x but have not tried it on rails 3.x

Rails :dependent => :destroy VS :dependent => :delete_all

:protect plugin --> http://ruido-blanco.net/blog/rails-dependent-protect-plugin-english/

Community
  • 1
  • 1
tronmcp
  • 346
  • 1
  • 6