Rails Nested Forms With Images

佐手、 提交于 2020-01-01 02:35:18

问题


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!


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/7599812/rails-nested-forms-with-images

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!