2013-11-21 28 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