12

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?

3
  • Hey, if you have got any idea of how to achieve file uploading using form_for while having other fields and labels, please share it here. Even I'm trying to make this work. Commented Feb 19, 2015 at 7:27
  • And it would be nice if there is no need to use any gem. Commented Feb 19, 2015 at 7:28
  • What happens if you try attr_accesible :name, :file and in your view <%= f.file_field :filename %>? Commented Mar 24, 2015 at 4:23

2 Answers 2

6

I will give you an example of 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

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.