11

So I'm building a nested form with an Campaigns model and a Sites model where Campaigns has_many Sites. In my Campaigns form I have:

<%= f.fields_for :sites do |builder| %>
    <%= render "site_fields", :f => builder %>
<% end %>

And then in the _site_fields.html.erb I have:

<div class="field">
 <%= f.label :title %><br />
 <%= f.text_field :title %>
</div>
 <%= f.label "Image"%><br>
 <%= f.file_field :image %>
<div class="field">
 <%= f.label :url %><br>
 <%= f.text_field :url %>
</div>

This all seems to work (shockingly) but I would like to have a preview of the image already uploaded for a particular site in the form. So where I have f.file_field :image I would also like to be able to show a preview of that image. The problem is that I don't seem to be able to access the current site being rendered because I'm using f.fields_for.

Any suggestions? I'm sure I'm missing something relatively simple.

Thanks in advance!

dshipper
  • 3,489
  • 4
  • 30
  • 41

2 Answers2

24

From the form helper object (in your case builder and f) you should be able to access the model object and the url your looking for like this:

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

The image in image_url depends on how you named the attribute, but for your sample this should be correct.

bass-t
  • 706
  • 7
  • 8
0

You may want to investigate the paperclip gem: https://github.com/thoughtbot/paperclip

It lets you do this to show a thumbnail of the existing picture.

<div class="field">
    <% if @thing.logo? %>
    <%= image_tag @thing.logo(:thumb) %><br/>
      Change
    <% end %>
    <%= f.label :logo %>
    <%= f.file_field :logo %>
  </div>
David
  • 844
  • 6
  • 14
  • Thanks! I'm actually using Paperclip right now, the question is where to get the @thing object since I'm not iterating through all of the sites that belong to a campaign anywhere - I'm just using fields_for. – dshipper Sep 29 '11 at 16:10
  • Can you post your controller code so I can work out what you need to do? – David Sep 29 '11 at 18:08