form_for帮助程序中的allow_destroy - Ruby on Rails

时间:2010-03-01 04:59:30

标签: ruby-on-rails paperclip

我是否可以使用适用于accepts_nested_attributes_for的“魔术”_destroy属性作为常规form_for帮助者?

我有一个我通过Paperclip上传的文件,我想要删除它。

1 个答案:

答案 0 :(得分:4)

确实如此 - 这是Haml的一个人为举例。

- form_for @obj, :url => obj_path, :method => :put do |f|
  - f.fields_for :sub, f.object.sub do |sub_form|
    - unless sub_form.object.new_record?
      %span.label= sub_form.label '_delete', 'Remove File'
      %span.input= sub_form.check_box '_delete'

在模型中:

accepts_nested_attributes_for :sub, :allow_destroy => true

编辑 - 新答案:是的,你可以,但它不那么“神奇”。您需要在保存之前在要检查的模型上定义自己的虚拟属性。这是使用嵌套属性的(未经测试)示例:

- form_for @obj do |f|
  - unless f.object.new_record?
    %span.label= f.label 'delete_file', 'Remove File'
    %span.input= f.check_box 'delete_file'

在模型中:

  attr_accessor :delete_file  # this is the "virtual attribute" that gets set by the checkbox
  before_update :remove_file
  def remove_file
    self.file = nil if self.delete_file == '1'
  end

有关虚拟属性的更详细说明,请参阅Railscasts #167