How to add multiple nested attributes to a multi file upload

寵の児 提交于 2019-12-24 18:43:53

问题


I am trying to set up a multi image upload with carrierwave. I am following the question Rails 4 multiple image or file upload using carrierwave and in particular the answer by @prograils https://stackoverflow.com/a/38769726/4779531.

I have an album.rb model and a diapo.rb model.

class Album < ApplicationRecord
  has_many :diapos
  accepts_nested_attributes_for :diapos, allow_destroy: true
end

+

class Diapo < ApplicationRecord
  belongs_to :album
  has_and_belongs_to_many :authors, :join_table => "diapos_authors"

  mount_uploader :file_name, DiapoUploader
end

In my Album controller I have the following attributes:

class Admin::AlbumsController < ApplicationController
.
.
.
  private

  def album_params
    params.require(:album).permit(:title, :series_id, diapos_attributes: [:id, :album_id, :file_name, :title, :alt, :author_ids, :copyright])
  end
end

In views/admin/albums/_form.html.erb I have:

  <%= f.fields_for :diapos, Diapo.new do |d| %>
    <div class='form-data'>
      <%= d.label :file_name, class: 'form-label' %>
      <%= d.file_field :file_name, multiple: true, name: "album[diapos_attributes][][file_name]", class: 'form-field' %>
    </div>
.
.
.
    <div class='form-data'>
      <%= d.label :copyright, class: 'form-label' %>
      <%= d.text_field :copyright, name: "album[diapos_attributes][][copyright]", class: 'form-field' %>
    </div>
  <% end %>

My multi-upload works. The images are written to the upload folder as well as their file name to the file_name field and their respective album_id to the album_id field of the diapos table in the database. Multiple records are created, one for each image I selected, but currently the copyright attribute is written only for the last record.

Why does that happen? How can I solve this?

I also would like to add the possibility to select the authors of the images:

    <div class='form-data'>
      <%= d.label :author, class: 'form-label' %>
      <%= d.select(:author_ids, Author.order('surname asc').map{|s| [s. name + ' ' + s.surname, s.id]}, {multiple: true, include_blank: true, name: "album[diapos_attributes][][author_ids]"}, {class: 'select-field-style'}) %>
    </div>

to the fields_for, but this too does not work and instead throws the error:

Rack::QueryParser::ParameterTypeError - expected Hash (got Array) for param 'diapos_attributes':'

Thank you very much in advance !

来源:https://stackoverflow.com/questions/59414743/how-to-add-multiple-nested-attributes-to-a-multi-file-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!