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>
1
  • 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 <span> inside of an <img> tag, despite the fact that an <img> tag has no closing tag. For the sake of clarity, please reformat your code and repost. Commented Jul 28, 2013 at 3:00

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>

2 Comments

Hmmm this is still not working for me getting an "undefined method `url' for #<ActionView::Helpers::FormBuilder:0x007fd078fcd5a0" Error message. Photos definitely have a url method though.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.