views:

126

answers:

1

Can I use the 'magic' _destroy attribute that works for accepts_nested_attributes_for for a regular form_for helper?

I have a file that I'm uploading via Paperclip and I'd like to have the option to delete it.

+2  A: 

Yes indeed - here's a contrived example in 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'

And in the model:

accepts_nested_attributes_for :sub, :allow_destroy => true

EDIT - NEW ANSWER: Yes, you can, but it's less "magical". You need to define your own virtual attribute on the model to be checked prior to the save. Here's an (untested) example that does not use nested attributes:

- 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'

And in the model:

  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

See Railscasts #167 for a more detailed explanation of virtual attributes.

Jonathan Julian
I meant without nested attributes - `for a regular form_for helper?`
yuval
Gotcha - I updated my answer with an example not using nested attributes.
Jonathan Julian
thank you very much!
yuval