0

I have polymorphic model Images and Post/Account etc.

models:

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

Controller:

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

Form(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"

The problem is that when you create a post everything works fine, but when I want to edit this post, I can see the buttons with existing images and a button for a new image. enter image description here

How I can in edit form remove the button for existing image and leave only the button for a new image. (Ideally, it would place the existing images with link to delete and button to attach new image). Thanks

4

1 回答 1

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]"}
于 2013-06-13T08:43:03.043 回答