Ruby On Rails: example of file_field on form_for

2019-06-16 04:42发布

问题:

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

<%= form_for(@photo, :multipart => true) do |f| %>

  <%= f.label :name %> 
  <%= f.text_field :name %>

  <%= f.file_field :file %>

  <%= f.submit %>

<% end %>

photos_controller.rb

def create
    @photo = Photo.new(params[:photo])

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?

回答1:

I remember that I used this to upload a xml file in Rails

view:

<%= form_tag({action: :upload}, multipart: true) do %>
   <%= file_field_tag 'xml_file' %>
   <%= submit_tag 'Submit' %>
<% end %>

controller:

def upload
    file_data = params[:xml_file]
end

It is using form_tag but it would not be hard to add other info into that form also.



回答2:

I will will you an example how I am using it I think it explains itself good enough, I hope this helps

 <%= form_for @item do |f|%>
    <%= f.file_field :photo, accept: 'image/png,image/jpeg'%>
 <% end %>

Let me know if you have any doubts