【问题标题】:cocoon neste image - how show image on edit page茧嵌套图像 - 如何在编辑页面上显示图像
【发布时间】:2016-09-06 20:16:45
【问题描述】:

我有一个接受图像模型嵌套属性的商家模型。我想在商家编辑页面上显示上传的图像,但我卡住了。

我收到以下错误:

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>

【问题讨论】:

  • 如果 f.object.image 可以尝试使用
  • 不错。这样可行。 =) 谢谢!! @BIlalKhan
  • 我可以为它添加一个答案,以便您接受它吗?

标签: ruby-on-rails simple-form nested-forms cocoon-gem


【解决方案1】:

你可以试试这个:

<%= image_tag(f.object.image_url(:thumb)) if f.object.image? %>

解释:

f.object 将是图像对象,如果它是新记录,则它不会包含图像。由于我们已经存在图像记录,所以我们可以添加图像检查?在 f.object 上。

我们也可以访问该图像的 image_url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-13
    相关资源
    最近更新 更多