我目前正在使用rails 3.2.13和ruby 1.9.3。
我正在尝试通过文件附件字段上传多个图像附件。到目前为止,我可以上传单个文件并成功显示图像。
_form.html.erb上有 add_object_link 功能可以创建其他文件附件字段,但不会在触发时显示或创建。
模型/ album.rb
attr_accessible :name, :photos_attributes, :gcategory_id
has_many :photos, :dependent => :destroy
accepts_nested_attributes_for :photos, :allow_destroy => true
模型/ photo.rb
belongs_to :album
查看/专辑/ _form.html.erb
<%= render :partial => 'layouts/error_messages', :locals => { :c => @album } %>
<p>
<%= f.label :gcategory_id %>
<br />
<%= f.collection_select :gcategory_id, Gcategory.all, :id, :name %>
<p>
<p>
<%= f.label :name %><br />
<%= f.text_field :name, { :class => 'title' } %>
</p>
<div class="album_photos">
<%= render :partial => 'album_photo', :collection => @album.photos %>
</div>
<div id="photos">
<% if @album.new_record? %>
<%= render :partial => 'photo', :locals => { :form => f, :photo => @album.photos.build } %>
<% else %>
<% @album.photos.each do |photo| %>
<%= image_tag photo.data.url(:small) %>
<% end %>
<% end %>
</div>
<%= add_object_link("New Photo", f, @album.photos.build, "photo", "#photos") %>
<p>
<%= f.submit %>
</p>
查看/专辑/ _photo.html.erb
<div class="photo">
<p>
<%= form.fields_for :photos, photo, :multiple => true, :child_index => (photo.new_record? ? "index_to_replace_with_js" : nil) do |photo_form| %>
<%= photo_form.file_field :data %>
<%= link_to_function "delete", "remove_field($(this), ('.photo'))" %><br/>
<% end %>
</p>
</div>
查看/专辑/ _album)photo.html.erb
<% unless album_photo.new_record? %>
<%= image_tag(album_photo.data.url(:small),:multiple => true, :alt => '') %>
<%= check_box_tag "photo_ids[]", album_photo.id %>
<% end rescue nil %>
助手/ albums_helper.rb
def add_object_link(name, form, object, partial, where)
html = render(:partial => partial, :locals => { :form => form}, :object => object)
link_to_function name, %{
var new_object_id = new Date().getTime() ;
var html = jQuery(#{js html}.replace(/index_to_replace_with_js/g, new_object_id)).hide();
html.appendTo(jQuery("#{where}")).slideDown('slow');
}
end
def js(data)
if data.respond_to? :to_json
data.to_json
else
data.inspect.to_json
end
end
控制器/ albums_controller.rb
def new
@album = Album.new
3.times { @album.photos.build }
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @album }
end
end
没有显示错误消息,并且能够上传单个文件。我找不到表单中的add_object_link没有创建其他文件附件字段的原因。
提前感谢您的帮助。