Search code examples
ruby-on-railssimple-formnested-formscocoon-gem

cocoon neste image - how show image on edit page


I have a Merchant model that accepts nested attributes for an image model.I want to display the uploaded image at the merchant edit page, but i'm stuck.

I received the follow error:

undefined method `image?' for nil:NilClass

Any ideas?

Merchant Model

class Merchant < ApplicationRecord
  has_many   :images, inverse_of: :merchant, dependent: :destroy
  accepts_nested_attributes_for :images, reject_if: :all_blank, allow_destroy:     true
end

Image Model

class Image < ApplicationRecord
  belongs_to :merchant
  mount_uploader :imagem, ImagemUploader
end

Merchant Controller

def new
  @merchant = Merchant.new
  @image = @merchant.images.build
end

Form

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

Partial

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

Solution

  • You can try this:

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

    Explanation:

    f.object will be the image object and if its the new record then it will not have the image present in it. As we have image record existed already, so we can add a check for image? on f.object.

    We can access image_url of that image too.