cocoon neste image - 如何在编辑页面上显示图像
问题描述:
我有一个接受图像模型的嵌套属性的商人模型。我想在商家编辑页面上显示上传的图像,但我卡住了。cocoon neste image - 如何在编辑页面上显示图像
我收到了如下错误:
undefined method `image?' for nil:NilClass
任何想法?
商家模型
class Merchant < ApplicationRecord
has_many :images, inverse_of: :merchant, dependent: :destroy
accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy: true
end
图像模型
class Image < ApplicationRecord
belongs_to :merchant
mount_uploader :imagem, ImagemUploader
end
商家控制器
def new
@merchant = Merchant.new
@image = @merchant.images.build
end
表格
<div id="images">
<%= f.simple_fields_for :images do |image_field| %>
<%= render partial: 'image_fields', locals: {f: image_field} %>
<% end %>
<%= link_to_add_association('Add image', f, :images, { class: 'button-admin__actions text--small' }) %>
</div>
部分
<div class="nested-fields">
**<%= image_tag(@image.image_url(:thumb)) if @image.image? %>**
<%= f.input :image,
accept: 'image/jpeg,image/gif,image/png',
required: true
%>
<%= link_to_remove_association('remove', f, { class: 'button-admin__actions text--small' }) %>
</div>
答
你可以试试这个:
<%= image_tag(f.object.image_url(:thumb)) if f.object.image? %>
说明:
f.object将图像对象,如果它的新记录,那么它不会有当前的图像在里面。由于我们已有图像记录,因此我们可以添加图像检查?在f.object上。
我们也可以访问该图片的image_url。
+0
不错。这样可行。 =)谢谢! – user1301037
+0
很高兴工作。谢谢 :) –
你可以请尝试使用 –
不错。这样可行。 =) 谢谢! @BIlalKhan – user1301037
我可以为它添加一个答案,以便您可以接受它? –