file: image.rb
1 2 3 4
has_attachment :content_type => :image belongs_to :post
file: _form.rhtml
1 2 3 4 5 6 7
<% for image in @post.images -%> <%= check_box 'image_delete', image.id, {}, 'yes', 'no' %> <% end -%> # => <input id="image_delete_1" type="checkbox" value="yes" name="image_delete[1]"/><input type="hidden" value="no" name="image_delete[1]"/>
file: posts_controller.rb
1 2 3 4
params[:image_delete].each do |id, value| Image.destroy id if value == 'yes' end if params[:image_delete]
Refactorings
No refactoring yet !
rpheath
October 24, 2007, October 24, 2007 21:49, permalink
I'm not completely sure I got the syntax right, but I think something like this might be better...
_form.rhtml
1 2 3 4
<% @post.images.each do |image| %> <%= check_box_tag "image_ids[]", image.id -%> <%= image.filename -%> <% end -%>
posts_controller.rb
1 2 3 4 5 6 7 8 9
# should this be in an image_controller? def destroy Image.destroy params[:image_ids] end # is this any better? def delete_images Post.find(params[:id]).images.delete(params[:image_ids]) end
I have used the attachment_fu plugin to allow images to be uploaded. It works really well, but I'm quite unsatisfied with the "technique" I used to allow images to be deleted. Is there a more elegant way to do this?