多态协会表单 - 创建新的或编辑现有的

问题描述:

我为公司的图像设置了多态关联。我想允许一个公司最多6张图片。如果图像已经创建,应该显示该图像,如果没有,它应该是一个上传字段。多态协会表单 - 创建新的或编辑现有的

型号设置:

class Company < ApplicationRecord 
    has_many :images, as: :imageable 
    accepts_nested_attributes_for :images 
end 

器设置:

def details 
    images_count = @company.images.count 
    build_number = 6 - images_count 
    build_number.times { @company.images.build } 
end 

在视图:

<%= form_for(@company) do |f| %> 
    <%= f.fields_for :images, multipart: true do |g| %> 
     <%= g.file_field :image %> 
    <% end %> 
<% end %> 

是否有可能检查,看看是否图像的特定实例已经创建,然后显示该图像?由于它是当前创建的,它将使用所有6个实例的file_field。

里面你的循环,你可以检查对象持久化

<%= form_for(@company) do |f| %> <%= f.fields_for :images, multipart: true do |g| %> <% if g.object.persisted? %> --- DISPLAY IMAGE <% else %> <%= g.file_field :image %> <% end %> <% end %> <% end %

+0

非常感谢你,这个工作。 我感谢您的帮助。 – connor