简体   繁体   English

多态关联表单-创建新的或编辑现有的

[英]Polymorphic Association Form - create new or edit existing

I have a polymorphic association set up for images on companies. 我为公司的图片建立了一个多态关联。 I want to allow for up to 6 images to a company. 我想给一家公司最多提供6张图片。 If an image has already been created, that should display that image, if not, it should be an upload field. 如果已创建图像,则应显示该图像,否则应显示为上传字段。

Model set up: 模型设置:

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

Controller set up: 控制器设置:

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

In the view: 在视图中:

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

Is it possible to check to see if that particular instance of image is already created, and then display that image? 是否可以检查该图像的特定实例是否已经创建,然后显示该图像? As it is currently created, it will use the file_field for all 6 instances. 由于当前已创建,它将对所有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 %

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM