2017-05-05 82 views
0

我爲公司的圖像設置了多態關聯。我想允許一個公司最多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。

回答

1

裏面你的循環,你可以檢查對象持久化

<%= 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