2010-03-01 75 views

回答

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

+0

我的意思是沒有嵌套屬性 - 「對於常規form_for幫手嗎?」 – 2010-03-01 07:35:45

+0

Gotcha - 我更新了我的答案,沒有使用嵌套屬性的例子。 – 2010-03-01 14:24:03

+0

非常感謝你! – 2010-03-03 09:37:21