Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails: example of file_field on form_for

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?

like image 293
M4ks Avatar asked Oct 21 '12 18:10

M4ks


1 Answers

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

like image 103
Jose Rafael Avatar answered Nov 01 '22 15:11

Jose Rafael