1

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>
  • Your snippet contains some _egregious_ formatting/indenting inconsistencies, some of which may bear a material impact on whether or not your code renders correctly. For instance, you've indented your `` inside of an `` tag, despite the fact that an `` tag has no closing tag. For the sake of clarity, please reformat your code and repost. – zeantsoi Jul 28 '13 at 03:00

2 Answers2

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).

Helio Santos
  • 6,606
  • 3
  • 25
  • 31
1

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>
zeantsoi
  • 25,857
  • 7
  • 69
  • 61
  • Hmmm this is still not working for me getting an "undefined method `url' for # – Pavlov's_Dawg Jul 28 '13 at 19:23
  • Ah, yes, I had a small typo which I've corrected. Rather than passing `p.url` as the value for the url hidden field, pass `photo.url` instead. Please advise as to whether or not that fixes the issue. – zeantsoi Jul 28 '13 at 21:33