Forum: Ruby on Rails Upload an image

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Eustáquio R. (Guest)
on 2006-04-10 17:40
Hello there. :-)

I have this view:

<%= form_tag({:action => 'create'}, :multipart => true) %>
   <table>
      <tr>
         <td>User</td><td><%= text_field("user","name") %></td>
      </tr>
      <tr>
         <td>Image</td><td><%= file_field("user","img") %></td>
      </tr>
   </table>
   <%= submit_tag "Create new user", :class => "submit" %>
<%= end_form_tag %>

I use this form to upload an image. On the controller I have:

   def create
      params[:user][:img] = params[:user][:img].read
      @user = User.new(params[:user])

      if @user.save
      ...

It reads the content of the file, saves it ok, but two questions:

First, is it ok to read on the controller? I saw samples on both the
controller and the model (on the model it just did not worked for me -
using img_field.read gives an error telling me

undefined method `read' for #<String:0xb651c3d4>

Second, how, with just those two fields, with no other field on the form
with content-type and so on (I saw some samples with that), make sure
that the user will only upload, for example, PNG files? I made some code
on the controller, but is there a way to do that on the model?

I saw on "Agile Web D. with Rails" that they used a

validates_format_of :content-type, :with => /^image/

on the model, but as I don't want to have a content_type field (and
don't want to), is there a way do validate this?

Thanks!
Roberto S. (Guest)
on 2006-04-10 18:15
(Received via mailing list)
I haven't read  you code, but why don't you use the file_column plugin ?
It
just works and solves a lot of problems related to image upload
Eustáquio R. (Guest)
on 2006-04-10 18:28
> It
> just works and solves a lot of problems related to image upload

Hi!

But does it handle the content-type checking?

Best regards,
Rizwan R. (Guest)
on 2006-04-11 01:25
(Received via mailing list)
Yes, it does handle all content type validations. Its handy!

Regards,
Rizwan
This topic is locked and can not be replied to.