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"?
Basically destroy runs any callbacks on the model while delete doesn't. Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.
By using destroy, you can delete the record from rails as well as its other existing dependencies. So in the context of our rails application, if we delete a book record using the destroy function, the authors associated with the book will also be deleted.
If you are looking for a way to it without SQL you should be able to use delete_all. See here for more information. The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.
Now, we can soft delete a comment by calling #destroy . In the next step we add the default scope which will exclude all deleted comments. And create only_deleted and with_deleted scopes. Now, we can soft delete comments and query non-deleted and deleted comments.
You should not use the delete
method on the Paragraph
object, but instead use the delete method of paragraphs
relation, like this:
post.paragraphs.delete(Paragraph.find(paragraph_id))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With