Stefan Schuchlenz
Stefan Schuchlenz

Reputation: 117

Rails3 nested_form - How to display current value in edit view?

I have created some nested form functionality using ryanb's nested_form gem and so far it works perfectly, but when a user edits an entry, I want to display the current value (in my case an image) that is present and allow for removing this existing entry but cannot figure out how to do that.

My code for the form so far:

=f.fields_for :images do |image_form|
    %p
      %label Image
      =image_form.file_field :image, :class => "form-control"
    %p=image_form.link_to_remove "<i class=\"fa fa-trash-o\"></i> Remove image".html_safe
  =f.link_to_add "<i class=\"fa fa-plus\"></i> Add image".html_safe, :images, :class => "btn btn-sm btn-default"

Upvotes: 0

Views: 53

Answers (1)

Stefan Schuchlenz
Stefan Schuchlenz

Reputation: 117

Managed to find a solution on my own (although not sure if this is the best possible way to do it):

I added a condition to check if the exiting object (in my case @posting) has images and then added a counter and the image_tag:

New code:

=f.fields_for :posting_images do |image_form|
  %p
    %label Image
    -if @posting.posting_images.size > 0
      -if [email protected]_images[@pi_count].nil?
        =image_tag @posting.posting_images[@pi_count].image, class: "img-thumbnail"
    =image_form.file_field :image, :class => "form-control"
  %p=image_form.link_to_remove "<i class=\"fa fa-trash-o\"></i> Remove image".html_safe
  -@pi_count = @pi_count + 1
=f.link_to_add "<i class=\"fa fa-plus\"></i> Add image".html_safe, :posting_images, :class => "btn btn-sm btn-default"

So far, it works as designed.

Notice: this is designed to work with Paperclip, for Carrierwave I guess the code looks slightly different but should be easily adaptable.

Upvotes: 1

Related Questions