我有一个带有Post模型的Rails应用程序,它使用Paperclip上传照片。我希望能够在该帖子edit
视图中删除帖子中的照片。以下代码从帖子中删除图像,但现在我无法创建新附件(新帖或现有帖子):
class Post < ActiveRecord::Base
has_attached_file :photo
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
attr_accessor :delete_photo
before_save :delete_photo, if: ->{ delete_photo == '1' && !photo.dirty? }
private
def delete_photo
self.photo = nil
end
end
和views/posts/edit.html.erb
:
<fieldset>
<ol class="post-fields-list">
<li>
<%= f.label :title %><br />
<%= f.text_field :title %>
</li>
<li>
<%= f.label :body %><br />
<%= f.text_area :body %>
</li>
<li><%= f.file_field :photo %></li>
<li>
<%= f.label :delete_image %><br />
<%= f.check_box :delete_photo %>
</li>
</ol>
</fieldset>
上面列表中的最后一个元素是创建删除图像的复选框。
如前所述,当我在模型中注释掉这一行时:
before_save :delete_photo, if: ->{ delete_photo == '1' && !photo.dirty? }
我可以创建附件没问题。
感谢您的帮助!
更新
我注意到f.check_box
生成的HTML看起来很奇怪:
<input name="post[delete_photo]" type="hidden" value="0" /><input id="post_delete_photo" name="post[delete_photo]" type="checkbox" value="1" />
答案 0 :(得分:2)
has_attached_file :photo
attr_accessor :delete_photo
before_validation { photo.clear if delete_photo == '1' }
无需破坏资产,Paperclip会这样做。
在表单中,form.check_box(:delete_asset)就足够了。
答案 1 :(得分:1)
而不是删除照片的attr_accessor :delete_photo
属性访问器,请尝试为delete_photo创建自己的getter和setter方法。
使用clear
方法删除附件,而不是分配nil
。
class Post < ActiveRecord::Base
has_attached_file :photo
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
before_save :delete_photo
def delete_photo
@delete_photo ||= "0"
end
def delete_photo=(value)
@delete_photo = value
end
private
def delete_photo
self.photo.clear = nil if @delete_photo == '1' && !self.photo.dirty?
end
end