gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for rails 4 没有删除

转载 作者:数据小太阳 更新时间:2023-10-29 06:26:49 24 4
gpt4 key购买 nike

我已经阅读和研究了大约 3 天。这是我最后的选择。

土地.rb:

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

上传.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

一切都会很美好:)

最佳答案

您还需要为嵌套模型允许 :_destroy 参数,因为当您选中表单中的“删除”复选框时会用到它。这是 Rails 标记必须销毁的模型实例的方式。

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

关于ruby-on-rails - accepts_nested_attributes_for rails 4 没有删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20117959/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com