views:

19

answers:

1

I would like to validate the presence of a file with paperclip. When I attempt to submit the form it rolls back, but for some reason it goes looking for a create.erb template which does not exist. I don't get any sort of error message either

class Image < ActiveRecord::Base
 has_attached_file :photo,
:styles => {
:thumb => "100x100#",
:small => "750x750>" } 
validates_attachment_presence :photo


class ImagesController < ApplicationController
before_filter :require_user, :only => [:new, :create]


def new
 @image = Image.new
end



 def create

 @image = Image.new(params[:image])
 @image.user = current_user
  if @image.save
    flash[:notice] = 'image uploaded'
    redirect_to :controller => "images", :action => "index" 
 end
end

def show
@image = Image.find(params[:id])
end

using the gem, version 2.3.3

+1  A: 

In your create you are not handling the case where @image.save returns false.

def create

  @image = Image.new(params[:image])
  @image.user = current_user
  if @image.save
    flash[:notice] = 'image uploaded'
    redirect_to :controller => "images", :action => "index" 
  else
    render :new # <== You forgot this.
  end
end

Without that piece it's actually trying to render create again, and fails.

hakunin
yeah that's right. Thanks
murdock
By the way, it's better to scope image to user when you build it, instead of assigning user later. Like this: `@image = current_user.images.build(params[:image])` (If user has_many images in your case.)
hakunin
So how can i customize the error message? In the controller I can put flash[:notice] = "upload failed". But I would like to be more specific like validates_attachment_presence :photo, :message => "include a file!". This doesn't work for me though.
murdock
the `:message` thing should work. (double checked in source: http://github.com/thoughtbot/paperclip/blob/master/lib/paperclip.rb#L325) Maybe a typo or something?
hakunin