在每个循环中使用Form_for [英] Using a Form_for with an each loop
问题描述
我正在尝试在Rails中创建一个表单,该表单允许用户使用复选框从较大的列表中选择某些照片。不幸的是,我还没有找到任何类似的例子,那里的大多数帖子都没有帮助。关于如何解决这个问题的任何想法?
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>
推荐答案
使用 form_form
。 但是,如果您愿意放弃 form_for
(而且根据您的标准,没有理由不应该这样做),您可以模仿通过在 <$ c $内嵌套 foreach
循环(每个循环包含 form_for
块)来描述的行为c> form_tag :
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>
这篇关于在每个循环中使用Form_for的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!