使用Paperclip进行多个文件上载

时间:2013-12-03 17:20:52

标签: ruby-on-rails-3

我看了http://www.emersonlackey.com/article/rails-paperclip-multiple-file-uploads并尝试将其应用到我的项目中。这就是我所拥有的:

property.rb

class Property < ActiveRecord::Base
  attr_accessible :avatar, :agent_id, :address, :neighborhood, :price, :photos
  belongs_to :agent
  has_attached_file :avatar, :styles => { :large => "1500x1500>", :thumb => "100x100>" }     
  has_many :photos
  accepts_nested_attributes_for :photos, :allow_destroy => true
end

photo.rb

class Photo < ActiveRecord::Base
  attr_accessible :avatar, :property_id
  belongs_to :property
  has_attached_file :avatar, :styles => { :large => "1500x1500>"}
end

properties_controller.rb

def new
 @property = Property.new
 5.times { @property.photos.build }
end

def edit
 @property = Property.find(params[:id])
 5.times { @property.photos.build }
end

new.html.erb

<h1>Create New Listing</h1>

 <%= form_for(:property, :url => {:action => 'create'}, :html => {:multipart => true}) 
 do|f| %>

 <%= f.file_field :avatar %>
 <% f.fields_for :photo do |f| %>
 <%= f.file_field :avatar, {:multiple => true} %>
 <% end %>

<table>
<tr>
  <th>Agent_ID</th>
  <td><%= f.text_field(:agent_id) %></td>
</tr>
<tr>
  <th>Address</th>
  <td><%= f.text_field(:address) %></td>
</tr>
<tr>
  <th>Neighborhood</th>
  <td><%= f.text_field(:neighborhood) %></td>
</tr>
<tr>
  <th>Price</th>
  <td><%= f.text_field(:price) %></td>
</tr>
</table>

<%= submit_tag("Create Listing") %>
<%= link_to 'Return to list', 'list' %>
   

我无法像他的视频中那样获得5个不同的文件字段。有谁知道我的代码有什么问题?我猜这个问题出现在表单页面中。 任何有关如何使其工作的帮助非常感谢。

由于

1 个答案:

答案 0 :(得分:0)

应:

<% f.fields_for :photo do |f| %>

不是:

<% f.fields_for :photos do |f| %>

另外,我不知道rails和paperclip是否支持multiple开箱即用的文件字段:http://initializd.com/blog/2013/3/upload-multiple-files-with-html5-rails-mongoid-paperclip-and-google-cloud-storage