Rails: radio button selection for nested forms objects

Posted by satynos on Stack Overflow See other posts from Stack Overflow or by satynos
Published on 2009-09-02T19:03:20Z Indexed on 2010/04/03 21:03 UTC
Read the original article Hit count: 569

I have the following form for photo_album which uses the nested forms feature of the Rails in saving the photos while updating the photo_album. And having trouble with the selection of radio button value. I want only one of the photos be able to select as the album cover, but due to the way rails produces form element ids and names, I am able to select all of the photos as album covers. Is there any workaround?

<% form_for @photo_album do |f| %>
  <%= f.error_messages %>

  <% @photo_album.photos.each do |photo| %>
    <% f.fields_for :photos, photo do |photo_fields| %>
      <p>
       <%= image_tag url_for_image_column(photo, "data", :thumb) %>
      </p>
      <p>
       <%= photo_fields.label :title %> 
       <%= photo_fields.text_field :title %>
      </p>
      <p>
       <%= photo_fields.label :body %>  
       <%= photo_fields.text_area :body %>
      </p>
      <p>
       <%= photo_fields.radio_button :cover, "1" %>
       <%= photo_fields.label :cover, 'Album Cover', :class => 'option' %>  
       <%= photo_fields.check_box :_delete %>
       <%= photo_fields.label :_delete, 'Delete', :class => 'option' %> 
      </p>  
     <% end %>
   <% end %>

   <p>
     <%= f.submit @photo_album.new_record? ? 'Create' : 'Update' %>
    </p>
<% end %>

And following is the html produced by rails (which is part of the problem) for radio buttons:

<p>
 <input type="radio" value="1" name="photo_album[photos_attributes][0][cover]" id="photo_album_photos_attributes_0_cover_1"/>
 <label for="photo_album_photos_attributes_0_cover" class="option">Album Cover</label>  
 <input type="hidden" value="0" name="photo_album[photos_attributes][0][_delete]"/><input type="checkbox" value="1" name="photo_album[photos_attributes][0][_delete]" id="photo_album_photos_attributes_0__delete"/>
 <label for="photo_album_photos_attributes_0__delete" class="option">Delete</label> 
</p>

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about nested-forms