Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove object from has_many but don't delete the original record in Rails?

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"?

like image 789
valk Avatar asked Sep 04 '14 08:09

valk


People also ask

What is the difference between delete and destroy in rails?

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.

How do I delete an object in rails?

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.

How remove data from table in rails?

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.

How do you implement soft delete in rails?

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.


1 Answers

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))
like image 105
Baldrick Avatar answered Oct 13 '22 15:10

Baldrick