gpt4 book ai didi

ruby-on-rails - rails : Destroy not working for nested attributes

转载 作者:行者123 更新时间:2023-12-02 04:45:51 31 4
gpt4 key购买 nike

我有一个应用程序,用户可以在其中创建一个他/她可以附加一些图片的画廊。为此,我使用载波,其结构如下。每个画廊有很多图片,每个图片有1个image

class Gallery < ActiveRecord::Base
has_many :pictures, dependent: :destroy
accepts_nested_attributes_for :pictures, allow_destroy: true;
end
class Picture < ActiveRecord::Base
belongs_to :gallery
mount_uploader :image, ImageUploader
end

图库和图片按以下方式上传和编辑

<ul>
<%= f.fields_for :pictures do |builder| %>
<li class="clearfix fields">
<% if p.object.image.length > 1 %>
<%= image_tag(p.object.image) %>
<% end %>
<%= p.file_field :image %>
<%= p.text_field :title %>
<% if p.object.image.length > 1 %>
<br />
<%= p.hidden_field :_destroy %>
<a href="#" class="delete-link">Remove picture</a>
<% end %>
</li>
<% end %>
</ul>

单击删除链接 时,_destroy 字段值设置为true(使用javascript)。这很好用。我还允许在我的强参数中使用 _destroy 属性,我看到它被传递到 GalleriesController

def gallery_params
params.require(:gallery).permit(:title, :synopsis, :thumb, pictures_attributes: [:image, :title, :id, :_destroy])
end

但不知何故,图片没有被删除。知道还需要添加什么,或者需要更正什么吗?

编辑,传递的参数看起来像这样

Parameters: {"utf8"=>"✓", "authenticity_token"=>"lTad77QCH7hDcSaKm0EFI90KhY+nVwNS4jRNADC7DSR1ATxszDwlHefWNyNEdVqdqpuvEh9PkBFnoPIfnp9JKw==", "gallery"=>{"title"=>"new one", "synopsis"=>"ssfjalsdj;fk", "pictures_attributes"=>{"0"=>{"title"=>"portfolio", "_destroy"=>"true", "id"=>"4"}, "1"=>{"title"=>""}}, "thumb_cache"=>""}, "commit"=>"Update Gallery", "id"=>"2"}

Controller 看起来像这样

class GalleriesController < ApplicationController
def update
@gallery.update(gallery_params)
redirect_to(gallery_path(@gallery))
end
end
class PicturesController < ApplicationController
def destroy
@picture = Picture.find(params[:id])
@picture.destroy
end
end

最佳答案

我会先改变一些东西:

1) 在您的图库模型中,true 之后有一个不必要的 ;

2) 在您的表单中,您在图片字段中传递 p 而不是 builder。在您的字段中使用 builder 或将 builder 更改为 p

3) 在您的图库 Controller 中,您是否在尝试更新之前设置了@gallery?如果没有在调用更新@gallery 之前放置此代码:@gallery = Gallery.find(params[:id])

您的图片 Controller 上的 destroy 方法可能不相关。当它嵌套在另一个模型中时,我不认为它会被调用。

完成这些操作后,还可以尝试更新其他内容(而不是破坏)并查看更改是否得到保存。这将有助于缩小问题范围。还要查看您的控制台,看看在传递参数哈希后是否有任何错误。分享您问题中的内容可能会有所帮助。

关于ruby-on-rails - rails : Destroy not working for nested attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250669/

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