Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Nested Forms With Images

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!

like image 574
dshipper Avatar asked Sep 29 '11 15:09

dshipper


1 Answers

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.

like image 151
bass-t Avatar answered Nov 15 '22 18:11

bass-t