Rails 4:如何使用carrierwave上传多个图像

我可以使用carrierwave上传文件,如下面的代码所示。 如何编辑代码,以便在一篇文章中上传最多3个文件的图像?

意见\文章\ new.html.erb

. . 
. .

views \ shared \ _article_form.html.erb

 . .  

. .

\型号\ article.rb

 class Article < ActiveRecord::Base belongs_to :user belongs_to :category has_many :photos, dependent: :destroy accepts_nested_attributes_for :photos . . end 

\型号\ photo.rb

 class Photo < ActiveRecord::Base belongs_to :article mount_uploader :image, ImageUploader validates :image, presence: true end 

\控制器\ articles_controller.rb

 class ArticlesController < ApplicationController . . def new @article = Article.new @category = Category.find(params[:category]) @article.category_id = @category.id @article.photos.build end def create @article = current_user.articles.build(article_params) if @article.save flash[:success] = "article created!" redirect_to current_user #root_url else @feed_items = [] render 'new' end end def edit @article = Article.find(params[:id]) end def update @article = Article.find(params[:id]) if @article.update(article_params) redirect_to current_user else render 'edit' end end . . private def article_params params.require(:article).permit(:content, :category_id, photos_attributes: [:id, :article_id, :image]) end . . end 

将您的新操作更改为:

 def new @article = Article.new @category = Category.find(params[:category]) @article.category_id = @category.id @photo = @article.photos.build end 

在您的file_field中,您需要使用multiple option因此您的表单将如下所示:

 <%= form_for(@article,:html => { :multipart => true }) do |f| %> // article fields <%= f.fields_for @photo do |p| %> <%= p.file_field :image, multiple: true %> <% end %> <% end %> 

更新

更改您的新动作并制作3张照片

 def new @article = Article.new @category = Category.find(params[:category]) @article.category_id = @category.id 3.times { @article.photos.build } end 

和你的表格

 <%= form_for(@article,:html => { :multipart => true }) do |f| %> // article fields <%= f.fields_for :photos do |p| %> <%= p.file_field :image %> <% end %> <% end %> 

此外,您还必须稍微修改模型才能拒绝空白值

 class Article < ActiveRecord::Base belongs_to :user belongs_to :category has_many :photos, dependent: :destroy accepts_nested_attributes_for :photos, reject_if: proc { |attributes| attributes[:image].blank? } . . end 

您只需要在form添加:html => { :multipart => true }即可上传多个文件。

 <%= form_for(@article,:html => { :multipart => true }) do |f| %> 

此外,您还必须将此行<%= p.file_field :image %>更改为<%= p.file_field :image, :multiple => true %>