目前使用 Rails 3.2 和 Carrierwave。
我有多个文件设置,但它需要多个文件字段,但我只想要一个文件字段。如果浏览器不支持 HTML5 多重属性,我将提供它作为默认值。
控制器
def new
@ad = Ad.new
5.times { @ad.images.build } // provides multiple file fields in the view.
end
def create
ad = Ad.new(params[:ad])
user = User.find(session[:user_id])
if user.ads << ad
flash[:notice] = "Ad successfully saved."
redirect_to ad_listing_path(ad.id, ad.slug)
else
render :new, :alert => "Ad was not saved."
end
end
Run Code Online (Sandbox Code Playgroud)
看法
<%= f.fields_for :images do |a| %>
<% if a.object.new_record? %>
<%= a.file_field :image, :multiple => true %><br>
<% end %>
<% …Run Code Online (Sandbox Code Playgroud)