I can upload a file with using carrierwave as shown in the following code. How can I edit the code to make it possible to upload images up to 3 files in one article?
views\articles\new.html.erb
.
.
<div class="span8">
<%= render 'shared/article_form' %>
</div>
.
.
views\shared\ _article_form.html.erb
.
.
<%= form_for(@article) do |f| %>
<div class="field">
<%= f.hidden_field :category_id %>
<%= f.fields_for :photos do |p| %>
<%= p.hidden_field :article_id %>
<% if p.object.image and p.object.image.file %>
<%= image_tag p.object.image.thumb.url %>
<p><%= p.object.image.file.filename %></p>
<% end %>
<%= p.file_field :image %>
<% end %>
<%= f.text_area :content, placeholder: "Enter contents..." %>
</div>
<%= f.submit class: "btn btn-large btn-primary" %>
<% end %>
.
.
\models\article.rb
class Article < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_many :photos, dependent: :destroy
accepts_nested_attributes_for :photos
.
.
end
\models\photo.rb
class Photo < ActiveRecord::Base
belongs_to :article
mount_uploader :image, ImageUploader
validates :image, presence: true
end
\controllers\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
You just have to add
:html => { :multipart => true }
to yourform
to upload multiple files.And also you have to change this line
<%= p.file_field :image %>
to<%= p.file_field :image, :multiple => true %>
Change your new action to this:
and in your file_field you need to use
multiple option
so your form will look like this:Update
Change your new action and build a photo 3 times
and your form
Also you'll have to modify your model a bit too in order to reject blank values