2010-07-09 70 views
0

我想用回形针验证文件的存在。当我尝试提交表单时,它会回滚,但出于某种原因,它会查找不存在的create.erb模板。我不明白使用宝石任何类型的错误信息或者回形针验证

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 

的,版本2.3.3

+0

你可以粘贴你的ImagesController吗? – 2010-07-09 16:33:05

回答

1

在你create你不处理,其中@ image.save返回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 

没有那块它实际上试图再次渲染create,并失败。

+0

是的,没错。谢谢 – murdock 2010-07-09 16:50:36

+0

顺便说一下,最好在构建时将图像的范围限定为用户,而不是稍后分配用户。像这样:'@image = current_user.images.build(params [:image])'(如果用户has_many图像在你的情况下) – 2010-07-09 16:52:22

+0

那么我如何定制错误信息呢?在控制器中,我可以将闪光灯[:notice] =“上传失败”。但我想更具体一些像validates_attachment_presence:photo,:message =>“包含文件!”。这虽然对我不起作用。 – murdock 2010-07-09 17:05:55