0

I have an organization model with an association has_one :uploads, as: :uploadable

It's a polymorphic relationship to

class Upload < ApplicationRecord
  include Uploaders::StandardUploader::Attachment.new(:file)
  belongs_to :uploadable, polymorphic: true, touch: true, optional: true
end

Everything works fine in terms of creating a record, but when I edit:

  = form.fields_for :upload, organization.upload do |form_upload|
    = form_upload.label :file
    = form_upload.file_field :file
      span Choose file...

The controller calls build_upload in the edit method, which builds a new association and actually destroys the existing one.

If I don't call build_upload, the form upload fiels are blank.

I'm at a loss of what's going on...what can I do to prevent the destroy on a has_one so the existing upload isn't lost?

What should I do to ensure the form fills in the existing upload?

Kevin Brown
  • 12,602
  • 34
  • 95
  • 155

2 Answers2

1

You should enable nested attributes to allow associated records to be updated through the parent one:

class UploadableModel < ApplicationRecord
  # ...
  accept_nested_attributes_for :upload
end

The fields_for should automatically generate the form fields in the nested attributes format ActiveRecord expects. See the examples in the fields_for API documentation below.

Janko
  • 8,985
  • 7
  • 34
  • 51
  • Thanks, Janko. You know what it was? I didn't have `reject_if: :all_blank` on that, so the form-updates were allowing the `:file` info to be nil'd...which in turn deleted the file (I think). I'm not sure if this is rails 5.1 specific. I'd like to update my question to be a little more clear. This is what I get for not stopping after 12 hours of coding. :) – Kevin Brown Feb 16 '18 at 12:37
0

Try setting association like

has_one :uploads, as: :uploadable, autosave: false
Evekay
  • 86
  • 4