问题
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>
回答1:
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).
回答2:
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>
来源:https://stackoverflow.com/questions/17903815/using-a-form-for-with-an-each-loop