2017-01-31 45 views
0

問題在於rails中的「強參數」。 我使用蜻蜓上傳圖片。param丟失或值爲空:gallery

問題是,如果我發送一個空的表單,我沒有得到任何錯誤處理參數。可能是什麼原因?

控制器:

還有一個也是方法「創建」,這在數據庫中保存圖像,並將用戶與圖片頁面。

def index 
    @gallery = Gallery.new 
    @galleries = Gallery.all 
end 

def create 
    @gallery = Gallery.new(gallery_params) 

    if @gallery.save 
    redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' } 
    else 
    redirect_to :back,   flash: { alert: "Your Image don't save." } 
    end 
end 

def gallery_params 
    params.require(:gallery).permit(:image) 
end 

瀏覽:

= form_for @gallery do |f| 
    = f.file_field :image 
    = f.submit 'Submit', class: 'btn bth-primary btn-lg' 

參數:

{"utf8"=>"✓", "authenticity_token"=>"8eotQtkj8SElqJLdHuOX8r+dWrCJRWTmVcyfd1mSLD/8MjWw/ElH/HCxZFSJ6oOWaxpbLbn4kAg5nlFycsgjHg==", "commit"=>"Submit"} 
+0

你是什麼意思「我沒有得到任何錯誤處理參數」? –

+1

你得到的是完美的,如預期的那樣。 –

+0

如果你的意思是你沒有得到任何驗證錯誤,那可能是因爲'image'字段不是強制性的。你應該發佈你的'圖庫'模型 –

回答

1

這是預期的行爲,請參閱ActionController::Parameters#require

文檔我通常在這種情況下什麼是趕上例外並顯示一條閃光信息以通知用戶。您也可以手動向模型添加錯誤。

def create 
    @gallery = Gallery.new(gallery_params) 

    if @gallery.save 
    redirect_to galleries_path, flash: { success: 'Your Image was successfully save.' } 
    else 
    redirect_to :back, flash: { alert: "Your Image don't save." } 
    end 
rescue ActionController::ParameterMissing => e 
    redirect_to :back, flash: { alert: "Please attach an image." } 
end 
相關問題