Search code examples
ruby-on-railsruby-on-rails-4associationssimple-formcocoon-gem

Rails 4: show uploaded image when editing form - getting undefined local variable or method


How do I show the uploaded image (associated) when editing the form? I tried to display like so:

_item_fields.haml

.nested-fields

  = image_tag f.img.url if f.img.url?
  = f.input :item

  = f.file_field :img

  = link_to_remove_association "remove item", f

Where it should display if there's a .url but I get this error:

undefined local variable or method 'img' #<SimpleForm::FormBuilder:0x007ff0eff8aee8>

_form.haml

= simple_form_for @model, html: {multipart: true} do |f|
  = f.simple_fields_for :items do |m|

    = render 'item_fields', f: m

    = link_to_add_association 'add item', f, :items
    = f.button :submit

In my show.haml, I have this

- @model.items.each do |m|
  - if m.img
    = image_tag m.img.url
  - else
    no image

this shows the image correctly.


Solution

  • I find this works: Inside the form use f.object to get the underlying object to build the correct url for the image_tag

    image_tag f.object.img.url 
    

    I'd post a reference, but it's not well documented. There's a bit of a discussion here.