Ask A Question


You’re not receiving notifications from this thread.

How to delete records in a join table?

Adrian DeGus asked in Rails

I'm using Refile for uploads and am having a tough time figuring out how to delete individual files. I need to display a delete link under each thumbnail, so my first thought was to do something like:

<% @document.document_attachments.each do |doc| %>
         <%= link_to attachment_image_tag(doc, :file), attachment_url(doc, :file), target: '_blank' %><br />
             <%= link_to 'Delete', document_attachment_path(doc, :file), method: :delete %>
<% end %>

I tried different paths/routes/controllers but nothing works. Maybe it's because I'm using a document_attachments join table?

class Document < ApplicationRecord
  has_many :document_attachments, dependent: :destroy
  accepts_attachments_for :document_attachments, attachment: :file, append: true

class DocumentAttachment < ApplicationRecord
  belongs_to :document  
  attachment :file

What's the best way to get these delete links working?


You'd be best off making a controller for it. Something like

resources :documents do
  resources :document_attachments

Then you can have that sub-controller for those DocumentAttachment records and can scope them to the document. And from there you can add the destroy action to lookup the Document, the DocumentAttachment, and then destroy it.

As you might have noticed, deleting files has pretty much nothing to do with Refile itself. Refile installs callbacks so that when you delete the database record, it will automatically delete the file along with it. So really you are doing just normal model deletes and Refile is just coming along for the ride.


Thanks Chris!

I actually had a document_attachments controller setup and was getting unilitialized constant errors, which through research I learned could be due to a routing conflict with Refile due to the similar name.

I'll try this again with a different name, maybe document_uploads, and hope the convention over configuration thing doesn't bite me.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 84,387+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.