具有嵌套表单的复制字段

时间:2013-04-30 19:36:15

标签: ruby-on-rails polymorphism nested-forms simple-form

我有多态模型ImagesPost / Account等。

模型:

class Image < ActiveRecord::Base
  ...
  belongs_to :imageable, polymorphic: true
  ...
end

class Post < ActiveRecord::Base
  ...
  has_many :images, as: :imageable
  accepts_nested_attributes_for :images
end

控制器:

class PostsController < ApplicationController
  ...
  def new
    @post = Post.new
    @post.images.build
  end

  def edit
    @post = Post.find(params[:id])
    @post.images.build
  end

  def create
    @post = Post.new(params[:post])
    @post.images.build(params[:image])
    ...
  end

  def update
    @post = Post.find(params[:id])
    @post.images.build(params[:image])
    ...
  end

表(simple_form)

= simple_form_for @post do |f|
  ...
  = f.simple_fields_for :images do |i| 
    = i.input :photo, as: :file, input_html: { multiple: 'multiple', name: "image[][photo]"}, label: t(:photo)
  ...
  = f.submit class: "btn"

问题是当你创建一个帖子时一切正常,但是当我想编辑这篇文章时,我可以看到带有现有图像的按钮和一个新图像的按钮。 enter image description here

如何在编辑表单中删除现有图像的按钮,只留下新图像的按钮。 (理想情况下,它会将现有图像与删除链接和按钮附加新图像)。感谢

1 个答案:

答案 0 :(得分:0)

确定。我找到了答案:

= f.fields_for :images do |i| 
    - if i.object.photo?
       = i.link_to_remove "Delete"
       = image_tag i.object.photo_url(:wide)
        %br
    - else
      = i.input :photo, as: :file, input_html: { multiple: 'multiple', name: "image[][photo]"}