我可以通过嵌套属性上传文件,但我收到此错误:
expected Hash (got Array) for param 'project_images_attributes/
我不认为它来自上传部分,但它来自此代码:
<% @project.project_images.each do |pic| %>
<%= f.simple_fields_for :project_images, pic do |image_fields| %>
<%= image_fields.label :_destroy, :class => "checkbox" do %>
<div class="img-controller-exist-preview">
<div class="img-controller-exist-img">
<%= image_tag pic.photo.url(:thumb) %>
</div>
<div class="img-controller-exist-delete">
<%= image_fields.check_box :_destroy %> <span>Delete</span>
</div>
</div>
<% end %>
<% end %>
<% end %>
因为,当我删除它时,我可以上传新照片。
这允许用户在编辑时删除现有图像。
这是我的完整形式:
<%= simple_form_for @project, html: { multipart: true } do |f| %>
<%= f.simple_fields_for :project_images, ProjectImage.new, child_index: ProjectImage.new.object_id do |ff| %>
<%= ff.label :photo, "Upload Photo" %>
<%= ff.file_field :photo, multiple: true, name: "project[project_images_attributes][][photo]" %>
<% end %>
<% @project.project_images.each do |pic| %>
<%= f.simple_fields_for :project_images, pic do |image_fields| %>
<%= image_fields.label :_destroy, :class => "checkbox" do %>
<div class="img-controller-exist-preview">
<div class="img-controller-exist-img">
<%= image_tag pic.photo.url(:thumb) %>
</div>
<div class="img-controller-exist-delete">
<%= image_fields.check_box :_destroy %> <span>Delete</span>
</div>
</div>
<% end %>
<% end %>
<% end %>
<%= f.submit %>
<% end %>
我测试了编辑项目并上传了要添加的图片,我收到错误。但如果我不上传任何内容,编辑工作。我可以删除照片和内容,但只有在我尝试上传内容时才会出现此错误。
ProjectImage模型:
class ProjectImage < ActiveRecord::Base
belongs_to :project
paperclip_opts = {
:styles => { :large => "800x800>", :medium => "x430>", :frontpage_thumb => "130x95#", :thumb => "150x150#" },
:convert_options => { :all => "-quality 75 -strip" }
}
has_attached_file :photo, paperclip_opts
validates_attachment_content_type :photo, content_type: /\Aimage\/.*\Z/
end
项目模型:
class Project < ActiveRecord::Base
has_many :project_images, dependent: :destroy
accepts_nested_attributes_for :project_images, allow_destroy: true
end
控制器:
def edit
@project = current_user.projects.find(params[:id])
end
def update
@project = current_user.projects.find(params[:id])
respond_to do |format|
if @project.update(project_params)
if params[:photos]
params[:photos].each { |image|
@project.project_images.create(photo: image)
}
end
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
答案 0 :(得分:0)
问题出在这一行
<%= f.simple_fields_for :project_images, pic do |image_fields| %>
fields_for
(或simple_fields_for
正在使用simple_form_for
)期望hash
作为第三个参数(选项),但您传递的是array
。