每个对象上传多张图片

Uploading multiple pictures per object

我正在尝试将图片添加到 Rails 教程中的 post,并将其扩展到我的需要。我有一个指南,它可以有很多与之相关的图片,而不是像教程中那样只有一张。

我想要一个上传图片的按钮。用户应该能够重复使用此按钮上传多张图片。

我正在尝试使用 accepts_nested_attributes,就像在这个答案中一样,但我不确定如何使用它:Rails 4 multiple image or file upload using carrierwave

我的向导模型:

class Guide < ActiveRecord::Base
  belongs_to :user
  has_many :guide_pics, dependent: :destroy
  accepts_nested_attributes_for :guide_pics
end

我的 GuidePic 型号:

class GuidePic < ActiveRecord::Base
  belongs_to :guide
  validates :guide_id, presence: true

  default_scope -> { order(created_at: :desc) }

  mount_uploader :picture, PictureUploader
end

我的编辑视图呈现图片上传器,它允许我 select 一张照片。我认为我不需要显示它的代码,但如果需要我可以提供它。当我点击上传时,它会进入我的 Guide 控制器。我的 GuidePics 控制器里什么都没有。

我认为我的 Guide 控制器必须更新图片,我正在尝试调用 guide_params

@guide.update_attributes guide_params

但我不明白我的 guide_params 函数需要做什么。我给了我一个错误 "unpermitted parameter: picture" :

def guide_params
   params.require(:guide).permit(:name, :city, :province, :country, :description, 
                                guide_pics_attributes: [:id, :guide_id, :picture]) 
end

另外,这是我上传图片的表格:

<!-- Upload pictures -->
<div class="col-md-2 col-md-offset-1">
   <strong>Upload A Picture</strong>
</div>
<div class="col-md-8 guide-edit-form guide-pic-upload">
  <%= form_for(@guide, html: { multipart: true }) do |f| %>
    <div class="picture" style="float:left;">
      <%= f.file_field :picture %>
    </div>
    <div style="">
      <%= f.submit "Upload", class: "btn btn-primary edit-guide-btn" %>
  </div>
  <% end %>
</div>

问题出在我的表格上。这是基于马特回答的解决方案:

<!-- Upload pictures -->
<div class="col-md-2 col-md-offset-1">
   <strong>Upload A Picture</strong>
</div>
<div class="col-md-8 guide-edit-form guide-pic-upload">
  <%= form_for(@guide, html: { multipart: true }) do |f| %>
    <%= f.fields_for :guide_pics, @guide.guide_pics.build do |p| %>
      <div class="picture" style="float:left;">
        <%= p.file_field :picture %>
      </div>
    <% end %>
    <div style="">
      <%= f.submit "Upload", class: "btn btn-primary edit-guide-btn" %>
  </div>
  <% end %>
</div>

再次阅读您链接的指南,您需要对表单的子项组件使用fields_for

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
    <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :title %>
    </div>

    <%= f.fields_for :post_attachments do |p| %>
        <div class="field">
            <%= p.label :avatar %><br>
            <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>
        </div>
    <% end %>

    <div class="actions">
        <%= f.submit %>
    </div>
<% end %>

所以在你的情况下,更像是:

<%= form_for(@guide, html: { multipart: true }) do |f| %>
    <%= f.fields_for :post_attachments do |p| %> 
        <div class="picture" style="float:left;">
            <%= p.file_field :picture %>
        </div>
    <% end %>
    <div style="">
        <%= f.submit "Upload", class: "btn btn-primary edit-guide-btn" %>
    </div>
<% end %>