Upload an image

Hello there. :slight_smile:

I have this view:

<%= form_tag({:action => ‘create’}, :multipart => true) %>

User <%= text_field("user","name") %>
Image <%= file_field("user","img") %>
<%= 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?


I haven’t read you code, but why don’t you use the file_column plugin ?
just works and solves a lot of problems related to image upload

just works and solves a lot of problems related to image upload


But does it handle the content-type checking?

Best regards,

Yes, it does handle all content type validations. Its handy!


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs