我有一个应用程序,用户可以创建一个gallery
他/她可以附上一些图片。我使用carrierwave来达到这个目的,它的结构如下。 每个gallery
有许多pictures
和每个picture
有1 image
。Rails:破坏不起作用的嵌套属性
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>
当点击delete-link
,所述_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"}
控制器的PARAMS这个样子
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
尝试在模型库上删除此'dependent :: destroy'。 我通常使用这个gem https://github.com/nathanvda/cocoon 来制作嵌套窗体:d – trnthanhtu
这是行不通的。 'dependent::destroy'是否有删除图片,如果我删除图库 – sjbuysse
什么都没有跳出来...这是一个伸手可及的距离,但是你用'1'而不是'真正'尝试了吗? –