这是使用 rails 4 中的载波从头开始上传多个图像的解决方案
只需按照以下步骤操作即可。
rails new multiple_image_upload_carrierwave
在宝石文件中
gem 'carrierwave'
bundle install
rails generate uploader Avatar
创建后脚手架
rails g scaffold post title:string
创建 post_attachment 脚手架
rails g scaffold post_attachment post_id:integer avatar:string
rake db:migrate
在 post.rb 中
class Post < ActiveRecord::Base
has_many :post_attachments
accepts_nested_attributes_for :post_attachments
end
在 post_attachment.rb 中
class PostAttachment < ActiveRecord::Base
mount_uploader :avatar, AvatarUploader
belongs_to :post
end
在 post_controller.rb
def show
@post_attachments = @post.post_attachments.all
end
def new
@post = Post.new
@post_attachment = @post.post_attachments.build
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
params[:post_attachments]['avatar'].each do |a|
@post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
end
format.html { redirect_to @post, notice: 'Post was successfully created.' }
else
format.html { render action: 'new' }
end
end
end
def update
respond_to do |format|
if @post.update(post_params)
params[:post_attachments]['avatar'].each do |a|
@post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
end
end
end
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to @post }
format.json { head :no_content }
end
end
private
def post_params
params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
end
在views/posts/_form.html.erb
<%= 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 %>
<% if params[:controller] == "post" && params[:action] == "edit" %>
<% @post.post_attachments.each do |p| %>
<%= image_tag p.avatar, :size => "150x150" %>
<% end %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在views/posts/show.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= @post.title %>
</p>
<% @post_attachments.each do |p| %>
<%= image_tag p.avatar_url, :size => "150x150" %>
<%= link_to "Destroy", p, method: :delete %>
<% end %>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
在 rails 3 中不需要定义强参数,并且您可以在模型和 accept_nested_attribute 中定义 attribute_accessible 来发布模型,因为在 rails 4 中不推荐使用属性可访问性。