valk
valk

Reputation: 9884

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

Upvotes: 39

Views: 30469

Answers (1)

Baldrick
Baldrick

Reputation: 24340

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))

Upvotes: 75

Related Questions