简体   繁体   中英

Using a Form_for with an each loop

I'm trying to create a form in Rails that allows a user to select certain photos from a larger list using checkboxes. Unfortunately, I haven't found any similar examples and most posts out there are unhelpful. Any ideas on how to solve this?

 <div>
  <%= form_for :photos, url: trip_path, method: "PUT"  do |f| %>
  <% @photos.each_with_index do |image, index|%>    
    <img src="<%= image.url %>" ><br>
      <span> <%=image.caption%> | <%=image.lat  %> | <%= image.long  %>
        <%= f.hidden_field "url", :value => image.url %>
        <%=check_box_tag('photo')  %>
      </span>
    <% end %>
    <%= f.submit 'Submit'  %>
  <% end %>
</div>

API docs states that a form_for

creates a form and a scope around a specific model object

so, you cannot use it with a collection.

A possible way to do it, is to use the form_tag instead of form_for and check_box_tag (which you already have).

The behavior you've depicted is categorically impossible using form_form . However , if you're willing to forgo form_for (and there's no reason why you shouldn't, given your criteria), you can imitate the behavior depicted by nesting a foreach loop – each loop containing a form_for block – within a form_tag :

<div>
    <%= form_tag trip_path, method: "PUT"  do |f| %>
        <% @photos.each do |photo|%>    
            <img src="<%= photo.url %>" ><br>
            <span> <%= photo.caption%> | <%= photo.lat  %> | <%= photo.long  %>
                <%= fields_for "photos[#{photo.id}]", photo do |p| %>
                    <%= p.hidden_field 'url', :value => photo.url %>
                    <%= p.check_box 'photo'
                <% end %>
            </span>
        <% end %>
        <%= f.submit 'Submit'  %>
    <% end %>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM