38

I have this:

Post.paragraphs << new_paragraph

And I need to remove paragraph by id = 3, so the following deletes the record completely:

Post.paragraphs.find(paragraph_id).destroy
# or
Post.paragraphs.find(paragraph_id).delete

I just need to remove a paragraph from has_many association. I tried to use delete and destroy. Both methods completely delete records from the associated tables. How can I just remove them from the "container"?

valk
  • 9,363
  • 12
  • 59
  • 79
  • Please note, that I forgot to remove the dependent: destroy. Anyway the answers below are great. – valk Sep 04 '14 at 08:42

1 Answers1

71

You should not use the delete method on the Paragraphobject, but instead use the delete method of paragraphs relation, like this:

post.paragraphs.delete(Paragraph.find(paragraph_id))
Baldrick
  • 23,882
  • 6
  • 74
  • 79
  • 12
    you can omit `Paragraph` and use `post.paragraphs.delete(paragraph_id)`. You can pass `Fixnum` or `String` values, it finds the records responding to the `id` and executes `delete` on them. – Roman Kiselenko Sep 04 '14 at 08:29
  • 1
    @Зелёный is there a way to make it work with an array of ids? – valk Sep 04 '14 at 08:34
  • 4
    @valk pass splat(*) array to delete method. Something like: `array = [1,2,3,4]` and now `post.paragraphs.delete(*array)` [read about it](http://apidock.com/rails/ActiveRecord/Associations/CollectionProxy/delete) – Roman Kiselenko Sep 04 '14 at 08:36
  • Doesn't this actually perform `delete` on the record, removing it from the database? The OP is asking how to remove the item from the array, not delete from the database. – Andrew Feb 17 '23 at 18:00
  • The record is not removed from the database, unless `dependant: :destroy` has been set in the `has_many` relation – Baldrick Feb 18 '23 at 19:07