Brian
Brian

Reputation: 61

How to upload file in nested form using ActiveStorage?

In my Project new view I have dynamically created nested forms (via Cocoon) to create new tasks and file_field to upload an image per task. When the form is submitted I create a new Project along with new tasks from project_params in my Project controller. But how can I use ActiveStorage to attach each tasks' image after the Project is created?

class Project < ApplicationRecord
  has_many :tasks
end

class Task < ApplicationRecord
  belongs_to :project
end

Nested form view

<%= form_for @project do |f| %>
    <%= f.fields_for :tasks do |ff| %>
        <%= ff.file_field :image %>
    <% end %>
<% end %>

Project controller

class ProjectController
  def create
    @project = Project.new(project_params)
    @project.save
    ...
    # How should I attach task images here?
  end
end

I can access individual images within params:

"tasks_attributes": {
  "0": { "image": ... },
  "1": { "image": ... }
}

One way is to loop through each @project.tasks and call .attach on them with image from the params above in the same order. But that seems error prone since params doesn't give me task ID to match with the saved task, so I worry I won't be always attaching the image to the right task. If some of the tasks didn't save to db due to being invalid, the 1-to-1 matching breaks down making this approach even more brittle.

Is there a better way?

Edit

For some reason it's working now. I couldn't tell whether I changed something or it's the original code...

Upvotes: 1

Views: 1905

Answers (1)

Kyle J. Dye
Kyle J. Dye

Reputation: 1724

Make sure you include the :id attribute under tasks_attributes in your Project Controller. Literally just ran into that myself!

Upvotes: 0

Related Questions