2 posts tagged “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
render :action => 'edit'
return
endif @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)を意味している。
→顧客「プルダウンが足りないので追加してください!」がなくなって(゚Д゚)ウマー
railsのfile_columnは便利だが一覧表示の各行で画像を表示しようとしてurl_for_file_columnを使うとエラーになる。
<% @memo.each do |memo| -%>
<tr>
<td><%= memo.title %></td>
<td><%if memo.image? %><img src="<%= url_for_file_column("memo", "image") %>")<%end%> </td>
</tr>
<% end -%>
具体的にはこんな感じ。
You have a nil object when you didn't expect it!
The error occurred while evaluating nil.image_relative_path
他の人は悩んでないので解決策があるのはわかっていたが、2日ほどはまった。
原因
url_for_file_columnメソッドはインスタンス変数対象じゃないと使えません。
# プラグインの公式のページの下のほうに英語で書いてあった気がする
解決方法
繰り返し操作の冒頭でローカル変数をインスタンス変数にぶち込みましょう。
そして、そのインスタンス変数を対象にurl_for_file_columnを使ってください。
<% @memo.each do |memo| -%>
<% @memo_image=memo %>
<tr>
<td><%= memo.title %></td>
<td><%if memo.image? %><img src="<%= url_for_file_column("memo_image", "image") %>")<%end%> </td>
</tr>
<% end -%>