2010-07-09 96 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