Ruby On Rails:form_for上的file_field的示例 [英] Ruby On Rails: example of file_field on form_for
问题描述
我在Rails中遇到文件上传问题.我找到了file_field :file
助手,可以与form_for(@some_model)
一起使用.但是,在这种情况下,我找不到任何用法,因为这些标签用于通过批量分配来创建/编辑某些模型. AFAIK无法将文件上传视为典型字段(请参阅
I came across file uploading problem in Rails. I found file_field :file
helper, that can be used with form_for(@some_model)
. However, I cannot find any usage for this case, as those tags are used to create/edit some model, by mass assigning. There is, AFAIK, no possibility to treat fileupload as typical field ( See File upload won't work in Ruby on Rails 3 using Multipart Form ). In such a case, manual operation on uploaded file is required. So, why would someone even want to puts a fileupload as a part of model editing?
photo.rb
class Photo < ActiveRecord::Base
attr_accessible :name, :filename,
end
photo_form.html.erb
photo_form.html.erb
<%= form_for(@photo, :multipart => true) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.file_field :file %>
<%= f.submit %>
<% end %>
photos_controller.rb
photos_controller.rb
def create
@photo = Photo.new(params[:photo])
上面的
行失败了,因为没有:file属性.必须在:params
之前对其进行处理并手动将其删除.再说一次-这些标签有实际用途吗?
line above fails, because theres no :file attribute. It must be handled before and manually removed from :params
. Once more - is there any real usage for such tags?
推荐答案
我记得我用它在Rails中上传xml文件
I remember that I used this to upload a xml file in Rails
视图:
<%= form_tag({action: :upload}, multipart: true) do %>
<%= file_field_tag 'xml_file' %>
<%= submit_tag 'Submit' %>
<% end %>
控制器:
def upload
file_data = params[:xml_file]
end
它正在使用form_tag,但也很难在该表单中添加其他信息.
It is using form_tag but it would not be hard to add other info into that form also.
这篇关于Ruby On Rails:form_for上的file_field的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!