我正在设置Carrierwave为我的嵌套模型上传图片。现在Rails没有错误,Carrierwave没有上传图像文件。我希望得到一些调试帮助。这是我的设置,想要一个带有一个或多个DeskImages的模型Desk:
desk.rb
class Desk < ActiveRecord::Base
has_many :desk_images, :inverse_of => :desk, :dependent => :destroy
accepts_nested_attributes_for :desk_images, allow_destroy: true
end
desk_image.rb
class DeskImage < ActiveRecord::Base
belongs_to :desk
mount_uploader :image, DeskImageUploader
end
desk_image_upload.rb
class DeskImageUploader < CarrierWave::Uploader::Base
....
end
desks_controller.rb
class DesksController < ApplicationController
def create
@desk = Desk.new(desk_params)
respond_to do |format|
if @desk.save
if params[:images]
params[:images].each { |image|
@desk.desk_images.create(image: image)
}
end
format.html { redirect_to @desk, notice: 'Desk was successfully created.' }
else
format.html { render :new }
end
end
end
/views/desks/_form.html.erb
<%= simple_form_for(@desk) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= file_field_tag "images[]", type: :file, multiple: true %>
<%= f.input :name %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
我做错了吗?
答案 0 :(得分:1)
使用带有carrierwave的嵌套表单总是很棘手。我们试着解决你的问题。
一切都取决于架构中的图像列类型。如果你也可以上传模式文件和你的Gem文件会很好。我会给你没有simple_form gem的解决方案。
我假设您安装了gem 'carrierwave'
,并且您的图片列位于表desk_images
中,其类型为字符串。如果您正确迁移,则还应该在架构中使用desk_id
整数类型。
在desk_image_upload.rb
中指定文件类型和上传图片的路径。我可以看到你的文件是空的,这意味着你没有运行rake generate uploader DeskImage
,它会自动填充you!的上传文件(小错字,应该是desk_image_uploader.rb
):< / p>
storage :file
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
检查desks_controller.rb
中的强对数并创建关联。
def show
@desk_images = @desk.desk_images.all
end
def new
@desk = Desk.new
@desk_images = @desk.desk_images.build
end
def create
@desk = Desk.new(desk_params)
respond_to do |format|
if @desk.save
params[:desk_images]['image'].each do |img|
@desk_images = @desk.desk_images.create!(:image => img)
end
format.html { redirect_to @desk, notice: 'Desk was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def desk_params
params.require(:desk).permit(:title, desk_images_attributes: [:id, :desk_id, :image])
end
在 /views/desks/_form.html.erb 中添加多部分表单数据:html => { :multipart => true })
<%= form_for(@desk, :html => { :multipart => true }) do |f| %>
<%= f.fields_for :desk_images do |d| %>
<div class="field">
<%= d.label :image %><br>
<%= d.file_field :image, :multiple => true, name: "desk_images[image][]" %>
</div>
<% end %>
注意:强>
如果您安装了gem,'carrierwave', github: 'carrierwaveuploader/carrierwave'
事情会发生变化。您需要在DB中使用JSON或数组列类型,并在上传器中使用mount_uploaders :images
。 (复数)请检查here
当您提交带有图像/图像的表单时,请检查您的控制台是否有参数。您还可以在日志文件夹中检查文件development.log
我希望它有所帮助