2013-11-21 29 views
25

我一直在閱讀和研究約3天。 這是我最後的手段。accep_nested_attributes_for rails 4沒有刪除

land.rb:

has_many :uploads , :dependent => :destroy 
accepts_nested_attributes_for :uploads, :allow_destroy => true,:reject_if => :all_blank 

upload.rb

belongs_to :land 

_land_form_partial.html.erb

<%= form_for land , :html => {:multipart => true} do |f| %> 

    <%= f.fields_for :uploads do |builder| %> 
     <div class="land_fields"> 
      <%= builder.label :filename, "Image" %> 
      <%= builder.text_field :filename %> <br/> 
      Delete: <%= builder.check_box :_destroy %> 
     </div> 
    <% end %> 
#... buttons and other fields 
<% end %> 

lands_controller.rb

def update 
    if @land.update_attributes(land_params) 
     flash[:success] = "Land updated" 
     redirect_to lands_path 
    else 
     flash[:alert] = @land.errors.full_messages.first 
     redirect_to edit_land_path 
    end 
    end 

def land_params 
    params.require(:land).permit(uploads_attributes: [ :id, :filename ] ) 
    end 

當我向文本字段添加內容並更新它時,所有更新都正確。如果我點擊複選框,它不會刪除該字段。

有人可以請說明這一點嗎?

另外我試過awesome_nested_fields仍然一切正常除了刪除實際記錄。

謝謝你提前。

編輯:解:(我喜歡把在問題解決的情況下,有人要查看它在移動,因爲我討厭當我看不到解決,立竿見影)

感謝@nTraum

def land_params 
    params.require(:land).permit(uploads_attributes: [ :id, :filename, :_destroy ] ) 
end 

一切都會花花公子:)

+1

我有同樣的問題,但在我的情況下,我省略:ID字段。然後,如果你想刪除一個嵌套模型,你需要允許:id和:_detroy嵌套模型的屬性。 –

回答

46

你需要讓你的嵌套模式:_destroy參數爲好,因爲這被用來當您檢查在表單中「刪除」複選框。這是Rails標記需要銷燬的模型實例的方式。

def land_params 
    params.require(:land).permit(uploads_attributes: [:id, :filename, :_destroy]) 
end 
+1

我認爲如果我說我愛你,這就是俗套。那真是血腥。再次感謝 :)。 –

+6

只需要注意:id和:_destroy參數是需要的,我發現後只添加:destory – Eric

+0

非常感謝@nTraum – Shiko

6

的OP沒有同樣的問題,因爲我,而是跨越這個問題沒有人來,對我來說,這是缺乏allow_destroy: true作爲在模型中accepts_nested_attributes調用的參數。

+0

這應該在文檔中更好地突出顯示 – retroGiant