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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With