file_columnでアップした画像を削除する方法

http://d.hatena.ne.jp/kusakari/20070530が参考になる。ファイルも消してくれるのは良いね。


画像削除は自前で行わなくても、nilを代入した上で save を呼ぶとファイルを消してくれるようなので、そのように修正。


では編集画面で画像だけ削除したい場合はどうすればよいか?


■view:_form.rhtml

<p><label for="memo_image">画像</label><br/>
<%= file_column_field 'memo', 'image' %><br/>
<%unless @memo.image == nil%>
<%= image_tag(url_for_file_column("memo", "image"))  %>
<input type="submit" name="delete_image" value="画像削除">
<%end%>
</p>


■controller:update

def update
   @memo = Memo.find(params[:id])

    #もし画像削除ボタンが押されたなら画像のみnilにする。
    if params[:delete_image]
      @memo.image = nil
      @memo.save
      render :action => 'edit'
      return
    end

    if @memo.update_attributes(params[:memo])
      flash[:notice] = 'Memo was successfully updated.'
      redirect_to :action => 'list'
    else
      render :action => 'edit'
    end
end

・formにsubmitが複数ある場合、実際に押されたボタンのvalueしかPOSTされない。
 従ってparams[:ボタン名]の値の有無で押下判定できるよ。
・render :actionで編集画面に戻した後、returnでメソッドを抜けましょう。


P.S.今日の気に入った処理<%= date_select 'article', 'start_date',start_year =>Date.today.year-1 %>
railsでは年のプルダウン選択肢をスマートに作れる。
・デフォルトでは今年を中心に前後5年を選択肢にする。
・sart_year、end_yearで開始年、終了年を指定できる。
・Date.today.year-1は昨年(2006)を意味している。
 →顧客「プルダウンが足りないので追加してください!」がなくなって(゚Д゚)ウマー