【问题标题】:accepts_nested_attributes_for rails 4 is not deletingaccept_nested_attributes_for rails 4 没有删除
【发布时间】:2013-11-21 10:10:42
【问题描述】:

我已经阅读和研究了大约 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

一切都将是花花公子:)

【问题讨论】:

  • 我遇到了同样的问题,但在我的情况下,我省略了 :id 字段。然后,如果要删除嵌套模型,则需要允许嵌套模型的 :id 和 :_detroy 属性。

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

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

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

【讨论】:

  • 如果我说我爱你,我觉得这很俗气。那是血腥的。再次感谢:)。
  • 请注意 :id 和 :_destroy 参数都是必需的,我只添加了 :destory 就发现了
【解决方案2】:

OP 没有和我一样的问题,但对于遇到这个问题的任何人来说,对我来说,这是因为模型中 accepts_nested_attributes 调用中没有 allow_destroy: true 作为参数。

【讨论】:

  • 这应该在文档中更好地突出显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
相关资源
最近更新 更多