我有一个带有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" />
has_attached_file :photo
attr_accessor :delete_photo
before_validation { photo.clear if delete_photo == '1' }
无需销毁资产,Paperclip即可完成。
在表单中,check_box(:delete_asset)就足够了。
尝试为delete_photo创建自己的getter和setter方法,而不是用于删除照片的attr_accessor :delete_photo
属性访问器。使用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